PARALLAX SX-Keya User Manual

WARRANTY
Parallax warrants its products against defects in materials and workmanship for a period of 90 days from receipt of product. If you discover a defect, Parallax will, at its option, repair or replace the merchandise, or refund the purchase price. Before returning the product to Parallax, call for a Return Merchandise Authorization (RMA) number. Write the RMA number on the outside of the box used to return the merchandise to Parallax. Please enclose the following along with the returned merchandise: your name, telephone number, shipping address, and a description of the problem. Parallax will return your product or its replacement using the same shipping method used to ship the product to Parallax.
If, within 14 days of having received your product, you find that it does not suit your needs, you may return it for a full refund. Parallax will refund the purchase price of the product, excluding shipping/handling costs. This guarantee is void if the product has been altered or damaged. See the Warranty section above for instructions on returning a product to Parallax.
COPYRIGHTS AND TRADEMARKS
This documentation is Copyright 2003 by Parallax, Inc. By downloading or obtaining a printed copy of this documentation or software you agree that it is to be used exclusively with Parallax products. Any other uses are not permitted and may represent a violation of Parallax copyrights, legally punishable according to Federal copyright or intellectual property laws. Any duplication of this documentation for commercial uses is expressly prohibited by Parallax, Inc. Check with Parallax for approval prior to duplicating any of our documentation in part or whole for any use.
SX-Key is a registered trademark of Parallax, Inc. If you decide to use the name SX-Key on your web page or in printed material, you must state that "SX-Key is a registered trademark of Parallax, Inc." Other brand and product names are trademarks or registered trademarks of their respective holders
ISBN 1-928982-01-8
DISCLAIMER OF LIABILITY
Parallax, Inc. is not responsible for special, incidental, or consequential damages resulting from any breach of warranty, or under any legal theory, including lost profits, downtime, goodwill, damage to or replacement of equipment or property, or any costs of recovering, reprogramming, or reproducing any data stored in or used with Parallax products. Parallax is also not responsible for any personal damage, including that to life and health, resulting from use of any of our products. You take full responsibility for your SX-Key/Blitz and SX chip application, no matter how life-threatening it may be.
WEB SITE AND DISCUSSION LISTS
The Parallax web site (www.parallax.com) has many downloads, products, customer applications and on-line ordering for the components used in this text. We also maintain several e-mail discussion lists for people interested in using Parallax products. These lists are accessible from www.parallax.com via the Support ? Discussion Groups menu. These are the lists that we operate:
§ SX Tech – Discussion of programming the SX microcontroller with Parallax assembly language tools and 3rd party BASIC and C compilers. Approximately 600 members.
§ BASIC Stamps – With over 2,500 subscribers, this list is widely utilized by engineers, hobbyists and students who share their BASIC Stamp projects and ask questions.
§ Stamps in Class – Created for educators and students, this list has 500 subscribers who discuss the use of the Stamps in Class curriculum in their courses. The list provides an opportunity for both students and educators to ask questions and get answers.
§ Parallax Educators – This focus group of 100 members consists exclusively of educators and those who contribute to the development of Stamps in Class. Parallax created this group to obtain feedback on our curricula and to provide a forum for educators to develop Teacher’s Guides.
§ Parallax Translators – Consisting of less than 10 people, the purpose of this list is to provide a conduit between Parallax and those who translate our documentation to languages other than English. Parallax provides editable Word documents to our translating partners and attempts to time the translations to coordinate with our publications.
§ Toddler Robot – A customer created this discussion list to discuss applications and programming of the Parallax Toddler robot.
§ Javelin Stamp – Discussion of application and design using the Javelin Stamp, a Parallax module that is programmed using a subset of Sun Microsystems’ Java® programming language. Approximately 250 members.
This manual is valid with the following software and firmware versions:
IDE: SXKey.exe software version 2.0
Firmware: SX-Key rev. F and SX-Blitz rev. A
The information herein will usually apply to newer versions but may not apply to older versions. New software can be obtained free on our web site (www.parallax.com). If you have any questions about what you need to upgrade your product, please contact Parallax.
Welcome
Thank you for purchasing the Parallax SX-Key/Blitz development system. We have done our best to produce a full-featured, yet easy to use development system for the SX microcontrollers. The result is the SX-Key and the SX-Blitz; very tiny, full-featured development tools with a Windows 95 and higher versions interface. We hope you will find this system as enjoyable to use as we do.
This manual is written for the SX20/28 chips with a date code of AB9921AA or later, and SX48/52 chips with a date code of AB0001A or later.
Older chips are not supported by this manual or the SX-Key development system.
Table of Contents
Table of Contents
1 Introduction to the SX-Key/Blitz Hardware ................................................................................................................13
2 Installing the SX-Key/Blitz Software.............................................................................................................................15
3 Quick Start Introduction..................................................................................................................................................17
3.1 Connecting and Downloading to the SX Tech Board .......................................................................................17
4 The SX-Key/Blitz Interface .............................................................................................................................................19
4.1 Starting the SX-Key/Blitz Software ....................................................................................................................19
4.1.1 Command Line Switches......................................................................................................................19
4.2 The SX Editor .........................................................................................................................................................20
4.3 The Menus..............................................................................................................................................................21
4.3.1 The File Menu ........................................................................................................................................21
4.3.2 The Edit Menu........................................................................................................................................22
4.3.3 The Run Menu........................................................................................................................................23
4.3.4 The Help Menu......................................................................................................................................25
4.4 The Windows.........................................................................................................................................................25
4.4.1 Print Window.........................................................................................................................................25
4.4.2 Find Window .........................................................................................................................................26
4.4.3 Find/Replace Window .........................................................................................................................26
4.4.4 Goto Line Number Window ................................................................................................................27
4.4.5 Configure Window................................................................................................................................28
5 The SX-Key Debugger......................................................................................................................................................31
5.1 The Debugger Windows.......................................................................................................................................31
5.1.1 The Registers Window..........................................................................................................................31
5.1.2 The Debug Window..............................................................................................................................34
5.1.3 The Watch Window...............................................................................................................................35
5.1.4 The Code/List File Window ................................................................................................................35
5.1.5 Modifying registers during debugging ..............................................................................................36
5.1.6 Breakpoints and the Current Instruction............................................................................................37
5.1.7 Setting the Program Counter ...............................................................................................................37
6 The Device Window.........................................................................................................................................................39
7 The SASM Assembler ......................................................................................................................................................43
7.1 The Structure of an SX Assembly Program........................................................................................................44
7.2 Comments ..............................................................................................................................................................45
7.3 Assembler Directives ............................................................................................................................................45
7.3.1 The EQU and = Directives....................................................................................................................47
7.3.2 The BREAK Directive............................................................................................................................47
7.3.3 The CASE and NOCASE Directives....................................................................................................47
7.3.4 The DEVICE Directive ..........................................................................................................................48
7.3.5 The DS Directive....................................................................................................................................51
7.3.6 The DW Directive..................................................................................................................................51
7.3.7 The END Directive ................................................................................................................................51
7.3.8 The ERROR Directive............................................................................................................................52
7.3.9 The FREQ Directive...............................................................................................................................52
7.3.10 The __FUSE and __FUSEX Directives.................................................................................................52
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 5
Table of Contents
7.3.11 The ID Directive.....................................................................................................................................53
7.3.12 The IF…ELSE…ENDIF Directive........................................................................................................53
7.3.13 The IF{N}DEF…ELSE…ENDIF Directives.........................................................................................54
7.3.14 The INCLUDE Directive.......................................................................................................................55
7.3.15 The IRC_CAL Directive........................................................................................................................56
7.3.16 The LIST Directive.................................................................................................................................56
7.3.17 The LPAGE Directive............................................................................................................................57
7.3.18 The ORG (Origin) Directive .................................................................................................................57
7.3.19 The RADIX Directive ............................................................................................................................58
7.3.20 The REPT Directive...............................................................................................................................58
7.3.21 The RESET Directive.............................................................................................................................59
7.3.22 The SPAC Directive...............................................................................................................................59
7.3.23 The TITLE and STITLE Directives.......................................................................................................60
7.3.24 The WATCH Directive..........................................................................................................................60
7.4 Macros.....................................................................................................................................................................62
7.4.1 The MACRO Directive..........................................................................................................................62
7.4.2 The ENDM Directive.............................................................................................................................63
7.4.3 The EXITM Directive.............................................................................................................................63
7.4.4 The LOCAL Directive ...........................................................................................................................63
7.4.5 The EXPAND and NOEXPAND Directives.......................................................................................63
7.4.6 Formal Parameters.................................................................................................................................64
7.4.7 Macro Invocation...................................................................................................................................65
7.4.8 Actual Values of Parameters................................................................................................................65
7.4.9 Token Pasting.........................................................................................................................................65
7.4.10 Quoting...................................................................................................................................................65
7.4.11 Macro Examples.....................................................................................................................................66
7.4.11.1 Simple Macros with no Parameters.....................................................................................66
7.4.12 Macros with Formal Parameters by Count ........................................................................................67
7.4.13 Macros with Formal Parameters by Name.........................................................................................68
7.5 Symbols...................................................................................................................................................................68
7.6 Labels ......................................................................................................................................................................69
7.7 Expressions.............................................................................................................................................................70
7.8 Data Types..............................................................................................................................................................72
7.9 The __SASM Pre-Defined Constant....................................................................................................................72
7.10 Files created by SASM ..........................................................................................................................................73
7.11 SASM Warning and Error Messages...................................................................................................................74
7.12 Reserved Words and Symbols.............................................................................................................................78
8 The Parallax Assembler...................................................................................................................................................79
8.1 The Structure of an SX Assembly Program........................................................................................................79
8.2 Assembler Directives ............................................................................................................................................79
8.2.1 The Device Directive.............................................................................................................................79
8.3 Symbols...................................................................................................................................................................81
8.4 Labels ......................................................................................................................................................................81
8.5 Expressions.............................................................................................................................................................81
8.6 Error Messages.......................................................................................................................................................81
Page 6 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
Table of Contents
8.7 Data Types..............................................................................................................................................................83
8.8 Reserved Words and Symbols.............................................................................................................................84
9 Upgrading Existing Code for SASM..............................................................................................................................85
10 SX Special Features and Coding Tips............................................................................................................................87
10.1 Introduction ...........................................................................................................................................................87
10.2 Port Configuration and Usage.............................................................................................................................87
10.2.1 Port Direction.........................................................................................................................................88
10.2.2 Pull-Up Resistors...................................................................................................................................89
10.2.3 Logic Level..............................................................................................................................................90
10.2.4 Schmitt-Trigger......................................................................................................................................91
10.2.5 Edge Detection.......................................................................................................................................92
10.2.6 Wakeup (Interrupt) on Edge Detection..............................................................................................93
10.2.7 Comparator ............................................................................................................................................95
10.3 The SX48/52 Multi-Function Timers ..................................................................................................................96
10.3.1 PWM Mode ............................................................................................................................................97
10.3.2 Software Timer Mode............................................................................................................................98
10.3.3 External Event Counter.........................................................................................................................98
10.3.4 Capture/Compare Mode......................................................................................................................98
10.4 All About Interrupts .............................................................................................................................................99
10.4.1 RTCC Rollover Interrupts...................................................................................................................100
10.5 Creating Tables....................................................................................................................................................103
10.5.1 Data Tables...........................................................................................................................................103
10.6 Dealing with Code Pages ...................................................................................................................................105
10.6.1 Branching Across Pages......................................................................................................................105
10.6.2 Calling Across Pages with Jump Tables...........................................................................................106
11 Appendix A: SX Features..............................................................................................................................................109
11.1 Introduction .........................................................................................................................................................109
11.2 CPU Features .......................................................................................................................................................109
11.3 Peripheral and I/O Features..............................................................................................................................109
12 Appendix B: Instruction Set Overview........................................................................................................................111
12.1 Introduction .........................................................................................................................................................111
12.2 Instruction Set Summary....................................................................................................................................111
12.3 Single Word Instructions....................................................................................................................................114
12.4 Multi-Word Instructions.....................................................................................................................................116
12.5 Instruction Set Quick Reference ........................................................................................................................118
13 Appendix C: SX Instruction Set....................................................................................................................................121
13.1 Introduction .........................................................................................................................................................121
14 Appendix D: The SX Tech Board..................................................................................................................................145
14.1 SX Tech Board Features......................................................................................................................................145
14.2 Connecting and Downloading...........................................................................................................................146
14.3 SX Tech Board Schematic ...................................................................................................................................147
15 Appendix E: SX Data Sheet...........................................................................................................................................149
15.1 Pinout Information and Descriptions...............................................................................................................149
15.2 Architecture..........................................................................................................................................................150
15.2.1 Instruction Pipeline.............................................................................................................................151
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 7
Table of Contents
15.2.2 Read-Modify-Write Considerations..................................................................................................151
15.2.3 Register Map Structure.......................................................................................................................151
15.2.4 Special Function Registers..................................................................................................................153
15.2.5 IND – The Indirect Register ($00)......................................................................................................153
15.2.6 Real Time Clock/Counter, WREG ($01)...........................................................................................153
15.2.7 PC – Program Counter ($02) ..............................................................................................................153
15.2.8 STATUS Register ($03)........................................................................................................................154
15.2.9 The FSR – File Select Register ($04)...................................................................................................155
15.2.10 Direct Addressing................................................................................................................................156
15.2.11 Indirect Addressing.............................................................................................................................160
15.2.12 The Bank Instruction...........................................................................................................................161
15.2.13 The Jump Instruction..........................................................................................................................162
15.2.14 Jumping Across Pages.........................................................................................................................163
15.2.15 The Call Instruction.............................................................................................................................163
15.2.16 Calling Across Pages...........................................................................................................................164
15.2.17 Returning from a subroutine..............................................................................................................164
15.2.18 The Stack...............................................................................................................................................165
15.2.19 The Push...............................................................................................................................................165
15.2.20 The Pop.................................................................................................................................................166
15.2.21 Stack Overflow.....................................................................................................................................166
15.2.22 Stack Underflow..................................................................................................................................166
15.2.23 Returns..................................................................................................................................................166
15.3 Port Configuration Registers .............................................................................................................................167
15.3.1 Port A Registers...................................................................................................................................167
15.3.1.1 TRIS_A – Data Direction Register......................................................................................167
15.3.1.2 LVL_A - TTL/CMOS Select Register ................................................................................167
15.3.1.3 PLP_A – Pull-Up Resistor Enable Register.......................................................................167
15.3.2 Port B Registers....................................................................................................................................168
15.3.2.1 TRIS_B – Data Direction Register ......................................................................................168
15.3.2.2 LVL_B - TTL/CMOS Select Register.................................................................................168
15.3.2.3 PLP_B – Pull-Up Resistor Enable Register .......................................................................168
15.3.2.4 ST_B – Schmitt-Trigger Enable Register ...........................................................................169
15.3.2.5 WKEN_B – Wake Up Enable Register...............................................................................169
15.3.2.6 WKED_B – Wake Up Edge Select Register.......................................................................169
15.3.2.7 WKPND_B – MIWU Pending Register .............................................................................169
15.3.2.8 CMP_B – Comparator Enable Register .............................................................................170
15.3.3 Port C Registers....................................................................................................................................170
15.3.3.1 TRIS_C – Data Direction Register......................................................................................170
15.3.3.2 LVL_C - TTL/CMOS Select Register.................................................................................170
15.3.3.3 PLP_C – Pull-Up Resistor Enable Register.......................................................................171
15.3.3.4 ST_C – Schmitt-Trigger Enable Register...........................................................................171
15.3.4 Port D and E Registers (SX48/52)......................................................................................................171
15.4 Control registers..................................................................................................................................................171
15.4.1 Mode register (SX20/28).....................................................................................................................171
15.4.2 Mode register (SX48/52).....................................................................................................................173
Page 8 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
Table of Contents
15.4.3 Option ...................................................................................................................................................174
15.4.4 Fuse Registers.......................................................................................................................................174
15.5 Interrupts..............................................................................................................................................................175
15.5.1 Description ...........................................................................................................................................175
15.5.2 The Specifics.........................................................................................................................................175
15.5.3 RTCC Interrupt....................................................................................................................................175
15.5.4 RB0-RB7 Interrupt ...............................................................................................................................176
15.6 Peripherals............................................................................................................................................................176
15.6.1 Oscillator Driver..................................................................................................................................176
15.6.1.1 LP, XT and HS Mode...........................................................................................................176
15.6.1.2 External RC Mode................................................................................................................178
15.6.1.3 Internal RC Mode.................................................................................................................179
16 Index ................................................................................................................................................................................181
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 9
Table of Contents
Figures
Figure 1 - Connecting the SX-Key/Blitz................................................................................................................................ 13
Figure 2 - First Time Running Window................................................................................................................................. 16
Figure 3 - Configure Window................................................................................................................................................. 16
Figure 4 - SX Tech Board with SX chip inserted................................................................................................................... 17
Figure 5 - The SX-Key Icon...................................................................................................................................................... 19
Figure 6 - The SX Editor........................................................................................................................................................... 20
Figure 7 - The Find Window................................................................................................................................................... 26
Figure 8 - The Find/Replace Window................................................................................................................................... 26
Figure 9 - The Goto Line Number Window.......................................................................................................................... 27
Figure 10 - The Configure Window....................................................................................................................................... 28
Figure 11 - The Debugger Windows...................................................................................................................................... 33
Figure 12 - The Device Window............................................................................................................................................. 39
Figure 13 - The Watch Window.............................................................................................................................................. 61
Figure 14 - TTL and CMOS Levels......................................................................................................................................... 90
Figure 15 - Schmitt Trigger Characteristics........................................................................................................................... 91
Figure 16 - SX48/52 Multi-Function Timers......................................................................................................................... 97
Figure 17 - The SX Tech Board.............................................................................................................................................. 145
Figure 18 - SX Tech Board Schematic................................................................................................................................... 147
Figure 19 - SX Pinouts............................................................................................................................................................ 149
Figure 20 - Instruction Pipeline ............................................................................................................................................ 151
Figure 21 - SX20/28 Register Map........................................................................................................................................ 152
Figure 22 - SX48/52 Register Map........................................................................................................................................ 152
Figure 23 - Rotate Right......................................................................................................................................................... 155
Figure 24 - Rotate Left............................................................................................................................................................ 155
Figure 25 - Global Register Addressing SX20/28/48/52 (direct) .................................................................................... 156
Figure 26 - SX20/28 General Purpose Register Addressing (direct) ............................................................................... 157
Figure 27 - SX48/52 General-Purpose Register addressing (direct)................................................................................ 158
Figure 28- SX20/28 Indirect register addressing................................................................................................................ 160
Figure 29 - SX48/52 Indirect register addressing............................................................................................................... 161
Figure 30 - The Jump Instruction.......................................................................................................................................... 162
Figure 31 - Jumping Across Pages........................................................................................................................................ 163
Figure 32 - The Call Instruction............................................................................................................................................ 164
Figure 33 - Calling Across Pages.......................................................................................................................................... 164
Figure 34 - The Push............................................................................................................................................................... 165
Figure 35 - The Pop ................................................................................................................................................................ 166
Figure 36 - Prescaler Division Ratios ................................................................................................................................... 174
Figure 37 - SX with External Crystal.................................................................................................................................... 176
Figure 38 - SX with External Ceramic Resonator ............................................................................................................... 177
Figure 39 - SX with External System Clock......................................................................................................................... 178
Figure 40 - External RC Mode............................................................................................................................................... 178
Page 10 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
Table of Contents
Tables
Table 1 - Editor Shortcut Keys................................................................................................................................................ 21
Table 2 - Debugger Buttons and Shortcut Keys.................................................................................................................... 35
Table 3 – Register Editing Keys.............................................................................................................................................. 36
Table 4 - SX Clock Options...................................................................................................................................................... 40
Table 5 - SASM Directives....................................................................................................................................................... 46
Table 6 - SX20/28 DEVICE Settings....................................................................................................................................... 49
Table 7 - SX48/52 DEVICE Settings....................................................................................................................................... 50
Table 8 – Comparison Operators........................................................................................................................................... 53
Table 9 - LIST Directive Options ............................................................................................................................................ 57
Table 10 - WATCH Display Formats ..................................................................................................................................... 60
Table 11 - Unary Operators..................................................................................................................................................... 71
Table 12 - Binary Operators .................................................................................................................................................... 71
Table 13 - Data Types............................................................................................................................................................... 72
Table 14 - SASM Error and Warning Messages.................................................................................................................... 75
Table 15 - SASM Reserved Words.......................................................................................................................................... 78
Table 16 - Parallax Assembler DEVICE Options.................................................................................................................. 80
Table 17 - Parallax Assembler Error Messages..................................................................................................................... 81
Table 18 - Parallax Assembler Reserved Words................................................................................................................... 84
Table 19 - Port Configuration Options................................................................................................................................... 87
Table 20 - MODE Register Settings........................................................................................................................................ 88
Table 21 - Interrupt Timing................................................................................................................................................... 102
Table 22 - SX Instruction Mnemonics .................................................................................................................................. 112
Table 23 - SX Single-Word Instructions............................................................................................................................... 114
Table 24 - SX Multi-Word Instructions................................................................................................................................ 116
Table 25 - SX Instruction Set Quick Reference.................................................................................................................... 118
Table 26 - Symbol and Value Operands .............................................................................................................................. 121
Table 27 - Flags and Registers............................................................................................................................................... 122
Table 28 - Binary Symbols..................................................................................................................................................... 122
Table 29 - SX Pins ................................................................................................................................................................... 150
Table 30 - Special Function Registers................................................................................................................................... 153
Table 31 - Bank Addresses and FSR Values........................................................................................................................ 159
Table 32 – SX20/28 Mode Register....................................................................................................................................... 172
Table 33 - SX48/52 Mode Register....................................................................................................................................... 173
Table 34 – External Component Selection for Crystals (Vdd = 5V)................................................................................. 177
Table 35 - Component Selection for Murata Ceramic Resonators (Vdd = 5.0 V)........................................................... 177
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 11
Table of Contents
Page 12 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
1 Introduction the SX-Key/Blitz Hardware
connector
OSC1OSC2VDDVS
S
Rev
F
S
X-K
e
y
OSC2
OSC1
MCLR
16
151819
17
Vss
1 Introduction to the SX-Key/Blitz Hardware
The SX-Key/Blitz hardware consists of the programmer unit, a four-pin programming interface and a standard, female serial port connector (DB9). The serial port connector should be plugged into an available standard, straight-through serial cable on an IBM-compatible PC. The four-pin connector on the SX-Key/Blitz board should be connected to four pins (VSS, VDD, OSC2 and OSC1) of the SX chip. Take care to connect it in the right orientation because this connector is not indexed.
Figure 1 - Connecting the SX-Key/Blitz
DB9 serial port
SX-Key or SX-Blitz programmer device
4-pin programming interface
RTCC
VDD
VSS
RA0 RA1 RA2
RB0 RB1 RB2 RB3
n.c.
n.c.
1
2
3
4
5
SX-28
6
7
8
9 20
10
11
12
13
14
+5+5
28
27
26
25
RC7
24
RC6
23
RC5
22
RC4
21
RC3 RC2RA3 RC1 RC0 RB7 RB6 RB5RB4
The SX-Key/Blitz is powered by the target circuit’s power supply and programming and debugging takes place over the oscillator pins. The power supply to the SX-Key/Blitz must be +5 V DC. If an external crystal, resonator or RC circuit is used, the SX-Key/Blitz can usually remain connected to the SX chip for programming purposes, without affecting the operation of the circuit. When debugging, the SX chip must not have an external clock source since the SX-Key’s internal programmable oscillator must be used. The SX-Blitz can only program SX chips, it cannot debug them.
Each SX microcontroller contains the necessary debugger hooks required to perform SX in-circuit debugging. No other supporting chips are necessary for the debugging process. During debugging, the SX-Key provides the oscillator signal to drive the SX microcontroller until such time that a breakpoint is hit or a single step or stop mode is initiated.
Figure 1 - Connecting the SX-Key/Blitz shows all the connections necessary to program, debug and run the SX microcontroller. An external resonator or crystal should be connected to the OSC1 and OSC2 pins to run the SX if the SX-Blitz is used, or if the SX-Key’s internal clock oscillator is not used.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 13
1 Introduction the SX-Key/Blitz Hardware
The SX-Blitz is designed to be a lower-cost device for programming the SX chips only (no debugging features are available). The SX-Blitz and SX-Key use the same interface software for programming, however, debugging features will not work with the SX-Blitz.
NOTE: Since the SX-Blitz and SX-Key function almost identically, they will be referred to as the SX­Key/Blitz, except where there are distinct differences.
Page 14 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
2 Installing the SX-Key/Blitz Software
2 Installing the SX-Key/Blitz Software
Before following the steps in the next chapter, you should first install the SX-Key/Blitz interface on your computer’s hard disk.
The SX-Key/Blitz Interface consists of the integrated editor, programmer, and debugger software. The following system requirements are a minimum for using the SX-Key/Blitz Interface:
80486 (or higher) IBM or compatible PC;
Windows 95 or higher operating system;
64 Mb of RAM;
3 Mb of available hard drive space;
CD-ROM drive, or access to the Internet;
1 available serial port.
To install the SX-Key/Blitz Interface:
1. Insert the Parallax CD-ROM in an available CD-ROM drive.
2. Use the CD's automatic browser to navigate to the Software section.
3. Expand the SX-Key & SX-Blitz folder.
4. Select the 18/28/48/52-pin SX chips (SXKey.exe) item.
5. Click on the Install button.
6. When prompted for the type of installation, select “Typical” in order to have the software installed
in the “Programs\Parallax Inc\SX-Key v2.0” folder. Select “Custom” when you want to change the default installation options, like the installation folder.
7. After the setup has finished, you will find a shortcut on the desktop, and a new “Parallax Inc”
program group in the Start menu.
You may also download the software from the Parallax web site. There are two different file versions available. One has a size of about 1.2 MB, and the other one of 4.6 MB. When you use the smaller one, it is necessary to have an Internet connection active while installing the software. Select any folder where the downloaded file shall be stored, and then run “Setup_SX-Key_Editor.exe” from this folder.
After you have successfully installed the SX-Key Editor and start it the first time, the dialog shown below opens:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 15
2 Installing the SX-Key/Blitz Software
Figure 2 - First Time Running Window
This is to remind you that you should review some basic configuration settings first. Click the OK but­ton, and press Ctrl-U to open the Configuration dialog shown to the right.
The only setting that is important for now is the selection of the serial port to which you have connected the SX-Key/Blitz.
Figure 3 - Configure Window
The configuration dialog allows you to select COM1, COM2, COM3, or COM4. Click the radio button in the “Serial Port” section that matches your installation. Make sure that the remaining options are set to the defaults as shown here, and then click “Okay” to
close the configuration dialog window. You may keep the SX-Key Editor active because you will need it to perform the next steps below.
Page 16 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
3 Quick Start Instruction
Area
3 Quick Start Introduction
This chapter is a quick start guide to connecting the SX-Key/Blitz and programming the SX microcontroller. Without even knowing how the SX-Key/Blitz and the SX chip work, you should be able to obtain satisfactory results from the steps that follow.
3.1 Connecting and Downloading to the SX Tech Board
In order to get familiar with how the SX-Key/Blitz Development System works, we’ll use the SX Tech Board to program and run a 28-pin SX chip.
Keep in mind that the SX Tech Board is not a programmer; rather the SX-Key/Blitz is the programmer/debugger device while the SX Tech board is a type of prototyping board. Follow these steps to connect and download a program:
Figure 4 - SX Tech Board with SX chip inserted
Power Jack
4-pin Programming Header
SX microcontroller (28-pin DIP) properly inserted into LIF socket.
1) Plug an SX28AC/DP into the 28-pin LIF socket on the SX Tech board as shown in Figure 4 - SX Tech
Board with SX chip inserted. Make sure it is oriented so that the half-moon notch in the chip faces away from the “Reset” button.
Power Indicator
Resonator Socket
Reset Button
Breadboard Prototyping
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 17
3 Quick Start Instruction
2) Connect the SX-Key/Blitz to a serial cable, and the serial cable to the serial (COM) port on the PC
that you have selected in the “Configure” dialog of the SX-Key/Blitz software.
3) Connect the SX-Key/Blitz to the 4-pin programming header with the VSS, VDD, OSC2 and OSC1
indicators lining up with the same indicators on the board Note that the programming header is not indexed. Therefore, double-check the correct orientation of the SX-Key/Blitz.
4) Insert one end of a 470 ohm resister into the RC7 socket (next to the upper left side of the
breadboard). Insert the other end of the resister into any hole in the breadboard.
5) Insert the shorter leg of an LED into the breadboard hole that is closest (horizontally) to the resister
leg. Insert the other leg of the LED into one of the VDD sockets (next to the top side of the bread­board).
6) Plug the power supply into the SX Tech board and into an available wall outlet. (The power
indicator should light up).
7) If it is not still active, start the SX-Key Editor now.
8) In the SX-Key Editor window, pull down the File menu and select “Open” (or press Ctrl-O). In the
browser window that appears, select and open the led28.src file. (The led28.src source code should appear in the SX-Key code window).
9) Pull down the Run menu and select Run (or press Ctrl-R). (The SX-Key software should assemble
the code and begin the programming process).
Congratulations! You have just programmed the SX microcontroller with the SX-Key/Blitz Development System. The program in the SX microcontroller should start running. The LED should flash on and off (if wired correctly).
In case you get an error message after you have selected the “Run” option, make sure that you did not modify the source code text in the editor window. If you did, simply re-load the original text by opening it again, and then repeat the steps described above.
Should an error message like “SX-Key not found on COMx” appear, check that you have selected the right serial port for communication with the SX-Key/Blitz, and that the serial cable is correctly connected to the PC, and to the SX-Key/Blitz on the other end. Also make sure that the SX-Key/Blitz is correctly placed on the 4-pin programming header, and that the SX Tech board is powered, i.e. the power indicator LED is active.
Page 18 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
4 The SX-Key/Blitz Interface
The SX-Key/Blitz interface is an integrated editor, programmer, and debugger. All the functions of the SX-Key and the SX-Blitz are available through this single software interface.
Throughout the rest of this manual, the SX-Key/Blitz interface will be referred to as the SX editor, or more simply, the editor.
4.1 Starting the SX-Key/Blitz Software
Figure 5 - The SX-Key Icon
During installation, a shortcut was automatically placed on the Windows desktop. Double-click on the SX-Key icon to launch the SX-Key/Blitz interface. In case, the Icon has been deleted from the desktop, you can also start the software via the Windows Start button. Navigate to the Parallax Inc. program group and select “SX-Key v2.0” there.
4.1.1 Command Line Switches
It is also possible to start the SX-Keys software together with parameters from a command line, e.g. using the Windows “Run…” option, or from the DOS command line. The Syntax is:
SxKey /<switch> {/<switch>…} <File name> When you specify a file name with a “.src” extension, the editor window will open, displaying the
contents of the source code file. When you specify an “.sxh” extension instead, the hex file will be opened into the device window.
The /r switch is used to open a file in read-only mode, i.e. it can be displayed but not modified in the editor or in the device window.
For example SxKey /r test.src opens the source file named “test”, and displays it in the editor window and SxKey /r test.sxh opens the hex file named “test”, and displays the device window. In both examples, the files are opened
read-only, i.e. they cannot be modified. In addition to the /r switch, the switches /1, /2, /3 and /4 are also defined. They are used to select the
COM port where the SX-Key/Blitz is attached. This will override the setting that has been recently
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 19
4 The SX-Key/Blitz Interface
made in the Configure window. It is recommended not to use these switches; they have been implemented for compatibility reasons only.
4.2 The SX Editor
Figure 6 - The SX Editor
The SX editor (see Figure 6 – The SX Editor, above) consists of a window containing a menu at the top, several shortcut buttons in a tool bar, a list of files that are currently open to the left, and a large text area to the right. In the status bar at the bottom, there is the row/column indicator, telling you at which row and column the cursor is currently located. The editor window is where your SX source code will be entered and edited. Standard Windows editing shortcut keys listed in Table 1 – Editor Shortcut Keys, below, may be used in addition to the commands in the Edit menu and the tool bar buttons to manipulate the source code.
Page 20 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
Table 1 - Editor Shortcut Keys
Function
Name
Copy Ctrl-C Copies selected text to the clipboard.
Cut Ctrl-X Cuts selected text to the clipboard.
Paste Ctrl-V Pastes clipboard contents.
Page Up PgUp Moves editor window one page up.
Page Down PgDn Move editor window one page down.
Begin of Line Home Move the cursor to column 1 in the current line
End of Line End Move the cursor behind the last character in the line.
Begin of Text Ctrl-Home Moves the cursor to row 1, column 1 in the editor window.
End of Text Ctrl-End Moves the cursor behind the last character of the text in the editor.
Tab Tab
Shortcut
Keys
Moves cursor to the next tab position. The tab position can be set in the configu­ration dialog.
4.3 The Menus
The SX editor menu bar contains four menus: File, Edit, Run and Help. These menus and their associated menu items are each described below. The most important functions can be also selected with one of the shortcut buttons in the tool bar that are also shown below. You will find details to some of the functions that can be selected via the menus later in this manual.
4.3.1 The File Menu
New Creates a new, empty edit window. Use this item to start a new source code
editing session. You may also click the shortcut button to create a new file. When you start the editor software, a blank session will be opened automatically, called “Blank 1”.
When you select “New” while another editing session is already open, it will be
moved to the “background” but it will still remain open. The open files list to the left displays the names of all open sessions.
Open… Opens a browse window to locate and load source code files. As an alternative,
click the shortcut button, or type Ctrl-O to open an existing file.
Again, if there is another session already open, it will be moved to the
background.
The names of all currently open files are listed in the open files list to the left of
the editor window. To switch between the sessions, left-click on the name of the file you want to see in the foreground.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 21
4 The SX-Key/Blitz Interface
Close Closes the source code file currently displayed in the editor window. You may
also right-click on the file name in the open files list, and then left-click on the prompt that is displayed to close a file.
When the file to be closed has been modified since the last save, a dialog box will
open allowing you to select whether or not to save the file or abort the close operation; i.e. keep the file open in the editor.
Save Saves the source code file currently displayed in the editor window. The shortcut
button or Ctrl-S can also be used to save the file.
Save As… Opens a Save As dialog box to save the source code currently displayed in the
editor window with a designated name.
Reopen Displays a list of the files that were most recently edited. You may then click on
one of the list items to open any of these files directly.
Print… Opens a print dialog box to print the source code currently displayed in the
editor window.
Exit Terminates the SX-Key/Blitz editor.
4.3.2 The Edit Menu
Undo This menu selection remains inactive until you make a change to the text in the
editor window. You can then revert the recent changes you have made to the text. Ctrl-Z also activates the Undo function.
Redo This is the opposite of the Undo function. It allows you to restore any changes
that were reverted by previous Undo actions. This selection remains inactive until you have used the Undo function at least once. Ctrl-Y also does a redo. After you have re-done an operation, you may undo it again.
Cut Cuts the selected text from the editor window and stores it in the Windows
clipboard. Ctrl-X is the equivalent keyboard entry. To select text, use one of the standard Windows methods, like moving the mouse
pointer across the text to be marked with the left mouse button pressed, or move the cursor with the cursor keys while the Shift key is held down.
In order to select complete lines in the text, move the mouse cursor to the left margin of the text area until it turns into an arrow, and then click the left mouse button. To mark two or more lines, mark the first line, and then drag the mouse up or down.
Page 22 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
Copy Copies the selected text from the editor window and stores it in the Windows
clipboard. Ctrl-C is the equivalent keyboard entry.
Paste Pastes the text from the Windows clipboard into the editor window starting at
the current cursor location. Alternatively, type Ctrl-V to paste text.
Find Opens the Find dialog box. Ctrl-F is the shortcut key for this function. Enter the
text (or part of it) you are looking for. If necessary, you may select the options to search for whole words only, or to match upper- and lower-case characters. You can also specify the search direction, i.e. if the search shall be performed begin­ning at the current cursor position towards the beginning or end of the text.
Find Next Finds the next occurrence of the specified text from the most recent Find
operation. F3 also performs this function.
Find/Replace… Opens the standard Windows replace dialog box. Ctrl-H is the shortcut key for
this function. Again, you have the options to search for whole words only, or to match upper- and lower-case characters.
Go to Line Number Opens a dialog box where you can enter a line number. Ctrl-G is the shortcut key
for this function. Click “Ok” to close the dialog, and to position the cursor to column 1 in the specified line.
Clear Errors When errors are encountered while assembling a source code file with the “new”
default SASM assembler, the lines with errors are highlighted, and the errors found are displayed in the status area. Use this menu selection to clear all error information.
4.3.3 The Run Menu
Assemble Assembles the code. You may also press Ctrl-A, or click the shortcut button to
start the assembly. When the code in the editor window could be assembled without errors, the message “Assembly Successful” will show up in the status bar.
When you use the default “new” SASM assembler and if there are any errors encountered in the code, a message box will open, telling you that errors were found. Click “Ok” to close the box. At the bottom of the editor window, you will notice a new area that contains a list of all errors found during assembly. The first error message line is highlighted, and the offending line in the source code is also automatically highlighted.
When there are two or more error lines, double-click on a line in order to jump to the offending line in the source code.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 23
4 The SX-Key/Blitz Interface
Make the necessary corrections to the source code, and assemble the code again, until no more errors are reported.
The assembler may also generate warning messages that are shown in the same area, together with any errors. With warnings, the code will be assembled, but it is a good idea to make the necessary corrections to the source code in order to avoid warnings.
NOTE: Before assembly, the current file will be saved automatically. If you have entered code into a new blank editor window, use the Save function to save the window contents under a specific name before starting the assembler.
Program Assembles the source code and programs the SX microcontroller (when the
assembly was successful). Ctrl-P also starts programming.
Run Assembles the source code, programs the SX and generates a clock signal. Ctrl-R
also runs a program.
Debug Assembles the source code, programs the SX, generates a clock signal and
initiates the debug mode. (Not used on the SX-Blitz). Ctrl-D also starts the debugging mode.
Debug (reenter) Assembles the source code, assumes that the SX device is already programmed
with the recent code to be debugged (i.e. does not program the SX again), generates a clock signal and enters the debug mode. (Not used on the SX-Blitz). Ctrl-Alt-D also re-enters the debugger.
This option is handy when you have previously terminated a debug session that you want to continue later without having made changes to the source code in the meantime.
As long as you add, remove or change WATCH or BREAK directives in the source code, you may still use this function to reenter the debugging session without downloading the program to the SX.
Any other changes to the source code require a new download, i.e. you must use the Debug option instead, to start the debugger.
Page 24 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
View List Assembles the source code, and then opens another window that shows the
contents of the list file generated by the assembler. Ctrl-L also displays the list file. The list file will be described in detail later in this manual (see Chapter 7.10 – Files Created by SASM).
Clock… Opens the clock control dialog box to allow the modification of the clock activity
and frequency. (Not used on the SX-Blitz). Ctrl-K also opens the clock dialog. With this function, the SX device’s clock is supplied by the SX-Key, and you may test the functionality of an application at various clock rates.
Device… Opens the device dialog box to allow modification of the SX microcontroller pa-
rameters. Ctrl-I also opens the device dialog box.
Configure… Opens the configuration dialog box to allow modification of the SX-Key/Blitz
programming interface. See Chapter 4.4.5 – Configure Window for configuration details. Ctrl-U also performs this operation.
4.3.4 The Help Menu
Contents Displays information on how to use the WATCH and BREAK directives. About Displays the SX-Key/Blitz Development System information box.
4.4 The Windows
Many menu items open up a separate window for further configuration or monitoring. These windows are described below.
4.4.1 Print Window
The print window is accessed via the Print… item on the File menu. It is the standard Windows Print dialog box that you know from other applications. It allows you to select which printer shall be used, and depending on the printer type, various options can be selected.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 25
4 The SX-Key/Blitz Interface
4.4.2 Find Window
Figure 7 - The Find Window
The Find window is accessed via the Find item on the Edit menu. Enter the text to be searched for in the “Find what” field. By default, the search direction is from the current cursor position to the bottom of the text. You may change this direction by clicking the “Up” radio button in the “Direction” group.
You may also specify if the search shall match whole words only and if upper/lower case characters shall be distinguished.
Click the “Find Next” button to start the search. When the pattern you have entered was found in the text, it will be highlighted.
Clicking “Find Next” again continues the search, and the next match will be selected in the text (if any). The Find window remains open, until you click the “Cancel” button.
After you have closed the Find window, you may still continue searching for the pattern most recently entered by selecting “Find Next” in the Edit menu, or simply hit the F3 key to continue the search.
4.4.3 Find/Replace Window
Figure 8 - The Find/Replace Window
Page 26 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
This window is similar to the Find window. Again, you can enter the text pattern to be searched for. In addition, you also can enter the replacement text.
Also, you may select if only whole words should be found and if the search shall be case-sensitive, or not.
Click the “Find Next” button to start the first search. When the pattern was found, it will be highlighted in the text.
Click the “Replace” button to replace the highlighted text with the replacement you have entered, or click “Find Next” to not alter the text, and to continue the search for the next matching pattern in the text.
When wish to replace all occurrences of the search pattern, click the “Replace All” button. You should use the replace all feature with extra caution because it replaces the search pattern in the whole text without further confirmation. You might consider activating the “whole words only” option to avoid unwanted replacements. Also note that “Replace All” always performs the search from the top of the text down to the bottom, where the find next always continues towards the bottom of the text.
4.4.4 Goto Line Number Window
Figure 9 - The Goto Line Number Window
This window is accessed via the Goto Line Number item on the Edit menu. Enter the line number where the cursor shall be positioned and click Ok. If necessary, the text in the editor window will be scrolled so that the line you have addressed will be visible and the cursor is placed in column 1 of this line.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 27
4 The SX-Key/Blitz Interface
4.4.5 Configure Window
Figure 10 - The Configure Window
This window is accessed via the Configure item on the Run menu and allows you to setup various properties of the software.
We have already addressed the Serial Port section at the top of the window. Click one of the radio buttons to select the COM port where your SX-Key/Blitz is connected.
When the option Create backup (.bak) files is selected, the editor will save a copy of the previous version whenever a modified source code file is saved.
The group Assembler Options allows you to configure the SASM assembler. When Use SASM is selected, the editor will call SASM to translate the source code in the editor window
into SX machine code. SASM is an enhanced version of Ubicom’s SASM assembler that has been adapted to the SX-Key Version 2 software. When you un-check this option, the original Parallax assembler will be invoked instead. Because there are some differences in language syntax between the two assemblers, it might be necessary to use the Parallax Assembler with older, legacy, source code (see Chapter 7 – The SASM Assembler and Chapter 8 – The Parallax Assembler for the differences between the assemblers).
Page 28 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
4 The SX-Key/Blitz Interface
Nevertheless, we strongly recommend that you use the SASM assembler for all new, or recently revised, source code. There are only a few modifications necessary to make legacy source code compatible with SASM (see Chapter 9 – Upgrading Existing Code for SASM).
When you choose to use the Parallax Assembler, by un-checking the "Use SASM" box, you will notice that a new group is shown at the top of the Options window, called IRC Calibration. Since the Parallax Assembler does not accept directives in the source code to set the value for IRC calibration, it is necessary to do this “outside” of the source code (see Chapter 15.6.1.3 – Internal RC Mode for details on IRC calibration).
When the option SASM files to “SASM Output dir” is selected, the files generated by SASM will be stored in the folder named “SASM Output” that is located in the folder where the SX-Key software has been installed. When the option is de-selected, the files will be stored in the folder where the source code files are located. See Chapter 7.10 – Files Generated by SASM for an explanation of the output files generated by SASM.
The option Local Labels Must Start In Col. 1 controls how SASM searches the source code for local labels (see Chapter 7.6 - Labels for more details on local labels). When the option is selected, local labels must start in the first column of a source code line. Otherwise, local labels may be indented.
When the Use New Editor option is un-checked, the text editor will change its style into the editor format that was part of earlier versions of the SX-Key software. As this “old” editor has much less features, it is recommended to always use the “new” editor. You will notice that the remaining selections in the Configure window will become invisible when you select the “old” editor.
The Enhanced Editor Options group contains various selections that allow you to configure the “new” editor.
Use the upper left and right arrow buttons to change the Font size of the text displayed in the editor window between 6 and 32 points.
The left and right arrow buttons below let you define the Tab size, i.e. by how many columns text shall be indented on TAB characters in the text (2, 4, 6, or 8 columns).
When Colored Code Keywords is checked, the editor will perform “syntax highlighting”, i.e. keywords in the source code text are displayed in color. Click on the colored button to the right of this option to open the Color dialog box. Here you can select the color that shall be used to highlight the keywords.
The Boldface Code Keywords gives you the option to let the editor display keywords in boldface. Boldfacing and color highlighting may also be combined.
When the Colored Comments option is checked, any comments in the source code text, i.e. text that starts with a semicolon, will be displayed in the color indicated to the right of this option. The color can be changed by clicking on the colored button.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 29
4 The SX-Key/Blitz Interface
The next option, Error BG Color, allows you to select the background color that shall be used to highlight any lines with errors after assembly. Again, click on the colored button to open the Color dialog box.
When the Jump To Assembly Error Line option is checked, the cursor will be positioned on the first line in the source code text after assembly, when errors were encountered. In addition, this line will be highlighted with the background color you have selected for the previous option.
After you have selected the required options, click “Okay” to accept them and to close the Configure window. Click “Cancel” instead, when you want to keep the options unchanged.
Page 30 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
5 The SX-Key Debugger
5 The SX-Key Debugger
The following is required to use the debug features:
SX-Key Rev. E (or greater) – The SX-Blitz cannot be used for debugging.
SX chip date code 9825 or later.
No external clock source connected to the SX chip. This includes oscillator packs, crystals,
resonators and RC circuits.
The SX-Key connected to the 4-pin programming header of the SX system to be debugged.
The SX system must be powered.
Source code to be debugged must include the RESET directive (see Chapter 7.3.21), must have WATCHDOG set to off, and must have 2 free words in the first page of code and 136 free words near the end of the last page of code (from 177 to 1FE, 377 to 3FE, 577 to 5FE, 777 to 7FE, 977 to 9FE, B77 to BFE, D77 to DFE, F77 to FFE), depending on the number of E2Flash pages. If an oscillator frequency of other than 50 MHz (the default) is desired, the source code should contain a FREQ directive (see Chapter 7.3.9) stating the frequency. When the FREQ directive is missing, the assembler will generate a warning message, indicating that 50 MHz is used by default.
NOTE: On some machines, it is necessary to close background software (graphics, screen savers, etc.), for proper operation of the DEBUG windows.
In order to invoke the debugger, select “Debug” from the “Run” menu, press Ctrl-D, or click the debug shortcut button in the tool bar.
The source code that is currently displayed in the editor window will be assembled, and if no errors were found, the program is automatically transferred into the program memory of the SX device.
If the transfer was successful, and if an IRC Calibration setting of 4 MHz was chosen, a small window with IRC information is displayed. You may ignore this information for now, and click “Okay” to close the window (see Chapter 15.6.1.3 – Internal RC Mode for details on IRC calibration).
Next, the debugger will start, and the windows will be displayed as shown in Figure 11 – The Debugger Windows.
5.1 The Debugger Windows
5.1.1 The Registers Window
This window contains all the data and describes the current state of the SX chip. The leftmost column within the Registers window displays the hexadecimal contents of global registers $00 through $0F.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 31
5 The SX-Key Debugger
Registers $10 through $1F of all other banks are shown in the columns on the far right of the window. The bank offsets are labeled at the top of each column and the current bank is highlighted in white. These columns will expand or contract to fit the number of RAM banks available in the SX. In this example, eight banks are shown.
The blue outline, shown here on the IND register, indicates the location that the FSR (file select register) is currently pointing at.
The second column, just to the right of the first sixteen registers, displays a binary representation of some of the registers, namely IND, Status, RA, RB, RC and 08 through 0F.
At the top center of the Registers window are the contents of the M register (hexadecimal) and the W register (both hexadecimal and binary) and the Interrupt and Skip flags. The Interrupt and Skip flags turn blue when set and white when cleared. The interrupt flag is set when an interrupt has occurred and cleared after the interrupt has been serviced. The Skip flag is set when the compare condition evaluates to true, i.e. when the skip will be performed. It is cleared when the condition evaluates to false, or after the skip has been performed.
Page 32 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
5 The SX-Key Debugger
Figure 11 - The Debugger Windows
The assembly code box under the M and W register display in the center of the Registers window lists several contiguous instructions at once. The first three digits on each line is the hexadecimal address in program memory, followed by the opcode and finally the assembly mnemonic and operand(s). This window normally shows the active section of code, around which the program counter (PC) points, however, the scroll bar allows movement of the window’s field of view to any section of code.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 33
5 The SX-Key Debugger
5.1.2 The Debug Window
The Debug window contains buttons for debugging functions. Each button has an associated shortcut key, as described in Table 2 – Debugger Buttons and Shortcut Keys, below.
The Step button (or Alt-S) will execute one machine instruction and update all registers.
The Walk button (or Alt-W) will execute one machine instruction after another in “slow motion”,
updating the display automatically and continuing until the Stop button is pressed, or a breakpoint is encountered. The delay time between instruction executions can be selected from the Update Speed drop-down list; with the range being from 1 (about one second) to Max (as fast as the computer can process it).
The Run button (or Alt-R) will initiate a full-speed execution of the program, and will continue until
a breakpoint is hit or the Stop or Reset buttons are pressed. The displayed registers will not update until the Poll button is pressed or execution is stopped.
The Poll button (or Alt-L) operates in one of two modes. If a breakpoint exists, the Poll button runs
the code at full speed halting execution at the break just long enough to update the display and then continues running. If a breakpoint is not set, the Poll button can be pressed only during run mode to get an instant update of the register displays.
The Stop button (or Alt-P) halts execution of a walk, run or poll operation and updates the display.
The Reset button (or Alt-T) returns the SX chip to its initial state and sets the program counter (PC)
to the location containing the reset vector.
The Registers, Code and Watch buttons (or Alt-E, Alt-D, Alt-C) bring the associated windows into
view if they were hidden. (The Debug window always stays on top).
The Reset Pos. button brings all windows into view, places them at their default positions, and
resizes them to the defaults.
The Quit button (or Alt-Q) closes the Debug windows and exits debug mode.
Page 34 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
5 The SX-Key Debugger
Table 2 - Debugger Buttons and Shortcut Keys
Button Shortcut
Step Alt-S Executes one machine instruction.
Walk Alt-W Executes multiple machine instructions in “slow motion”.
Run Alt-R Executes instructions in full speed.
Poll Alt-L
Stop Alt-P Halts execution of a walk or run operation.
Reset Alt-T Resets the SX chip.
Registers Alt-E Brings Registers window into view.
Code Alt-D Brings Code window into view.
Watch Alt-C Brings Watch window into view.
Reset Pos. none Resets all debugger windows to their defaults.
Quit Alt-Q Closes the Debug Windows and exits debug mode.
unction
Updates display then continues execution. Can be used synchronously or asynchronously.
The Debug windows are highly active and interactive displays. Every time the display is updated (after a step, walk, poll or stop operation), each register that was modified since the previous update is high­lighted in red. This provides a clear indication of what the last instruction accomplished. Similarly, each bit that was changed is marked in red within all registers shown in binary. Additionally, the assembly code box and Code window highlights the instruction pointed to by the program counter (PC) in blue, and a breakpoint in red.
5.1.3 The Watch Window
The Watch window displays the contents of selected registers in a user-defined format. The values in the Watch window can be modified using the same methods described in Section 5.1.5 – Modifying registers during debugging, below. In addition, the numerical values in the Watch window can be modified in any format (binary, hexadecimal or decimal) regardless of the displayed format. Simply precede the input value with a %, $, or nothing, respectively. String values can only be modified by entering new strings. See the Watch directive section in Chapter 7.3.23 – The Watch Directive for information of defining watches.
5.1.4 The Code/List File Window
This window displays the contents of the list file generated by the assembler (see Chapter 7.10 – Files Created by SASM for more information about the list file). While a program is executed in single steps,
or in walk mode, the instruction that is currently executed is highlighted with a blue background. If a breakpoint is defined, this line is highlighted with a red background. The Code/List File window has a toolbar with several shortcut buttons. These buttons have the
following meanings:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 35
5 The SX-Key Debugger
Jump to Code: Scrolls the window to display the first line that assembles into CPU instructions.
Jump to Reset Line: Scrolls the window to display the line of code that will be executed upon
reset. This line will be highlighted blue.
Jump to Breakpoint: Scrolls the window to display the line with the breakpoint. This line will be highlighted red. When no breakpoint is defined, this button is inactive.
Jump to “Next Run” Line: Scrolls the window to display the next line of code that will be executed. The line will be highlighted blue.
Jump to Main: Scrolls the window to display the label called “Main”, if there is one.
5.1.5 Modifying registers during debugging
Any register, bits within registers, or flags can be modified using the mouse and keyboard (see Table 3 – Register Editing Keys for a summary of the editing keys). To modify a register (in hexadecimal), first
click on it or use the tab and cursor keys to move the focus to that register. (The focus is indicated by a blinking, black highlight within the register). Next, type in the new hexadecimal value on the keyboard and press the enter, space, backspace or arrow keys to write the value to the register. The new value will appear in the selected register, highlighted in red to indicate a change.
To change a bit or flag in the binary registers, simply click the mouse on the appropriate bit. The bit will toggle to the opposite state and will be highlighted in red to indicate a change. Click on the INT or SKIP flags to toggle their state. The INT and SKIP flags, unlike registers, do not indicate a change with a red highlight. Instead, a blue color indicates the flag is set, while a white color indicates the flag is cleared.
If a register’s contents are changed by accident, press the ESC (escape) key to restore its previous value.
Table 3 – Register Editing Keys
Key
TAB Move focus to new control block and ignore any changes to previous register.
Cursor Keys Move focus to new register within control and write any changes to previous register.
Space Same as cursor down.
Backspace Same as cursor up.
Enter Write changes to register.
ESC
Changes register value to previous value, if it has been changed by the user. This will not work if the enter, space, backspace or cursor keys have been pressed first.
Page 36 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
5 The SX-Key Debugger
5.1.6 Breakpoints and the Current Instruction
The assembly code box and Code/List File window display a breakpoint as a red highlighted line and the next instruction to be executed as a blue highlighted line.
The breakpoint can be set to a new line by clicking the mouse button once on the desired line in either the assembly code box, or in the Code/List File window. Clicking the mouse button again will remove the breakpoint. Only one breakpoint can be set at a time.
5.1.7 Setting the Program Counter
The next instruction to execute can be set to a new line by double-clicking the mouse button on the desired line in the assembly code box or the Code/List File window. Additionally, the program counter (PC) register’s contents can be manually modified via the keyboard to set the next instruction to execute.
If a breakpoint and the program counter should both be on the same line, it will become multicolored. The first third of the line will be highlighted in red (to indicate the breakpoint) and the last two thirds of the line will be highlighted in blue (to indicate the next line to execute).
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 37
5 The SX-Key Debugger
Page 38 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
6 The Device Window
6 The Device Window
The Device window is accessed via the Device item on the Run menu, or by pressing Ctrl-I. You may also click the Device shortcut button in the editor’s toolbar. This window allows you to specify all the device settings for the SX microcontroller you are using, program and verify or read the contents of the device and load or save object files for the SX.
Figure 12 - The Device Window
All data shown in this window reflect the settings specified in the DEVICE line(s) of the source code (if it had been assembled just before opening this window), the settings in the loaded object code or the settings read out of the device itself. You may modify these settings manually and program or reprogram the chip, however, those modifications will not be reflected in the source code.
The Device section (SX18, SX28 or SX48/52) should be set to the SX microcontroller that is currently used. It is important to make this selection first because depending on the device selected, some other options become active or inactive.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 39
6 The Device Window
Description
NOTE: To select an SX20 device, click on the SX18 selection. SX18 devices are no longer manufactured by Ubicom
The Oscillator section specifies the fuse settings for the various clock sources, and oscillator modes that are available in the SX devices, similar to the directives that can be given in the source code. Please note that any fuse settings defined in the source code will be overwritten by the options selected here when the SX controller is programmed from the Device window. See Table 4 - SX Clock Options, below, for a summary of the available clock options.
Table 4 - SX Clock Options
Setting
HS1…3 XT1…2
LP1…2
External RC Specifies special drive for external resistor-capacitor clock circuits.
Internal
32 KHz…4 MHz
Specifies the oscillator drive capacity for high speed, medium speed crystal/resonator, and low power crystal/resonator clocks.
Specifies internal clock at indicated frequency.
In the Brownout section, you can specify the threshold voltage for a brownout reset or you may also turn off brownout detection completely.
The Reset Timer section (SX48/52 devices only) should be set to the desired reset delay. The reset delay is the amount of time the SX48/52 waits after a reset condition before executing the first program instruction. This setting is useful for enabling a faster response after a sleep operation. It is critical to test this with your final circuit since the reset delay is intended to make sure the external oscillator (crystal, resonator, R/C circuit, etc) is running and stabilized before the first instruction executes.
The Options section allows you to set various fuse options. Turbo mode and enhanced Stack + OPTION can only be selected for SX20/28 devices because SX48/52 devices always have these options active, whereas the Sleep Clock option can only be selected for SX48/52 devices.
When you activate the Code Protect feature, the contents of the SX chip (except for the ID) cannot be read back once it is programmed. Actually, when you read a code-protected device, meaningless data will be read back instead.
The ID and E2Flash sections display the values contained in the ID and E2Flash memory (the program memory) respectively.
The Program button initiates programming the SX chip with the assembled source code or the object code loaded into the Device window.
Use the Verify and Read buttons to verify the code in the SX against that shown in the Device window or to simply read the SX’s code into the Device window. These options are valuable should the code in an SX chip be questionable or unknown. Note that verifies will fail and reads will not reveal the true code
Page 40 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
6 The Device Window
or fuse settings if the SX chip was programmed with the code-protect fuse on. The ID field will always read properly, however.
The Load Hex and Save Hex buttons may be used to load or save assembled object files. If an object file is desired for a particular source program, simply load the source into the SX-Key editor, assemble it, open the Device window and click the Save Hex button. To program SX chips with an object file, use the Load Hex button on the Device window to load that file and then click the Program button.
Former versions of the SX-Key software had options in the Device window to set the IRC calibration, i.e. the calibration of the internal RC oscillator of the SX devices. This feature is now defined by a directive in the SASM assembler source code (see Chapter 15.6.1.3 – Internal RC Mode for details on the IRC calibration).
Click the Cancel button to close the device window.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 41
6 The Device Window
Page 42 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7 The SASM Assembler
This part of the manual describes the SASM assembler (integrated in the SX-Key Version 2.0 software) which is an enhanced version of Ubicom’s SASM.
The SX-Key software 2.0 and above supports both assemblers, the Ubicom SASM which is described in this chapter, and the Parallax Assembler which is described briefly in the next chapter.
Although you may select between both assemblers using the Configure dialog, it is highly suggested that you design all new code for SASM, and use the Parallax Assembler for “old” source code only, written under previous versions of the SX-Key software. You should even consider changing such code so that is assembles under SASM, or both because there are only a few minor modifications necessary for that purpose (see Chapter 9 – Upgrading Existing Code for SASM).
The main task of the assembler is to translate the contents of program source code files into code that can be programmed into the SX device’s E²Flash memory, where it is then executed at run-time.
The assembler also generates various output files that will be described in Chapter 7.10 – Files created by SASM.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 43
7 The SASM Assembler
Comments
Directives
Mnemonics
Lab
els
7.1 The Structure of an SX Assembly Program
A typical SX assembly language program contains comments, directives, symbols, labels, expressions and mnemonic instructions as shown in the sample below.
;--------------------------------------­;| XYZ Controller Version 2.1 | ;| (C) 1997 Company, Inc. | ;| Written by John Doe 12/01/97 | ;---------------------------------------
; =====Device data and Equates===== DEVICE SX28, OSCHS2, PROTECT ID ’V2.1’ RESET Main
pvdd EQU rc.1 ;vdd data_out_a EQU %1100
; =====Variables===== org $08 ;point to start of ram
xbit_in ds 1 ;pc communication data data_low ds 1 data_high ds 1 pulses ds 1 ;programming pulse count
; =====Begin code===== org $000
; =====JUMP TABLE===== jmp read ;$00 = read device jmp program ;$01 = program device jmp pin_mode ;$07 = pin mode
; =====PC COMMUNICATION===== get_data mov w,#19 ;ready clrb dc ;set receive mode jmp send_data:bits ;receive word into data
send_okay mov w,#$00 mov data_low,w mov w,#4 jmp send_data:go
send_data mov w,#19 ;ready null+0+16outdata+1 clc ;clear carry for stop bit :go setb dc ;set transmit mode
Symbols
Operands
Page 44 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.2 Comments
Comments are optional messages usually used to document the source code. They are ignored by the assembler and may be placed almost anywhere in the program. A comment must be preceded by a semicolon (;). The following demonstrates examples of comments.
; This program controls the GPX513v driver chip ; mov counter, 120 ;initialize loop counter
Notice that a comment can be placed on the same line as an instruction (see the third line above). Since the assembler ignores everything that appears to the right of a semicolon, a comment may only appear on its own line or to the right of an instruction.
For debugging purposes, lines of code can be hidden from the assembler, or commented out, simply by inserting a semicolon before the first character of the line.
7.3 Assembler Directives
Assembler directives are special instructions to the assembler to help define symbols, set device options or indicate how the code should be assembled. Directives may appear within the source code, like assembly instructions, however, since they are instructions to the assembler and not the SX microcontroller, they are not actually assembled into the final machine language program. Table 5 – SASM Directives, below, describes the available SASM Assembler directives.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 45
7 The SASM Assembler
Table 5 - SASM Directives
= / SET BREAK Defines a run-time breakpoint. BREAK CASE / NOCASE DEVICE / FUSES /
PROCESSOR DS / RES / ZERO DW Defines words in EEPROM. DW data {,data…} END
EQU / GLOBAL ERROR Defines an assemble-time error or warning. ERROR ‘error text’ EXPAND /
NOEXPAND
FREQ
__FUSE / __FUSEX
ID IF
{ELSE} ENDIF IFDEF/IFNDEF {ELSE} ENDIF
INCLUDE
IRC_CAL Specifies the calibration value for the internal RC oscillator.
LIST Controls the list format, and sets certain options
LOCAL
LPAGE Inserts a form feed at this point in the list file. LPAGE MACRO {EXITM} ENDM
Assigns or reassigns a value to a symbol. This directive is used to create and manipulate assemble-time variables.
Specifies that the following instructions should be, or should not be, case sensitive. Sets SX device options. These directives usually precede all other direc­tives and instructions. Increments the memory pointer ($) by value. Used to reserve RAM and E2Flash during assembly.
Marks the end of the source code. All text following the END will be ignored by the assembler. Assigns a value to a symbol. This directive is used to create assemble­time variables.
Specifies that the following macro instructions should be, or should not be, expanded in the list file. (See section 7.4.5 – The EXPAND and NOEXPAND Directives for a detailed description.) Specifies the clock frequency, in Hz, to be generated by the SX-Key during debugging. Defines FUSE and FUSEX words as explicit expression values. Not recommended for use. Assigns a value to the 8-byte ID word in the SX. The text argument may be up to 8 characters and should be enclosed in apostrophes.
Conditional assembly and alternate conditional assembly block.
Conditional assembly and alternate conditional assembly block based upon symbol definitions.
Includes a source code file, i.e. the INCLUDE directive is replaced by the contents of the file specified with the directive.
Declares the labels named after the directive as private symbols that are only available inside a macro body. (See section 7.4.4 – The LOCAL directive for a detailed description.)
Defines a macro. (See section 7.4 – Macros for a detailed description.)
symbol = value
{NO}CASE
DEVICE setting {,setting…}
symbol DS value
END
symbol EQU value
{NO}EXPAND
FREQ n __FUSE expression
__FUSEX expression ID ‘text’ IF condition
{ELSE} ENDIF IF{N}DEF symbol {ELSE} ENDIF
INCLUDE “<file path>” IRC_CAL IRC_SLOW |
IRC_4MHZ | IRC_FAST LIST {C=cols} {F=format} {L=NONE|NOPAGE|PAGE} {N=lines} {P=processor} {Q=message number} {R=radix} {X=ON|OFF}
LOCAL <label>[, <label>]…
label MACRO {value} {EXITM} ENDM
Page 46 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
ORG
RADIX Specifies the radix for numeric constants REPT
ENDR RESET Specifies the starting location of the program in the SX’s memory. RESET label SPAC Inserts blank lines in the listing file SPAC <number> STITLE Synonym for TITLE STITLE “<string>” TITLE Defines a program listing title TITLE “<string>” WATCH Defines a symbol to watch during debugging. WATCH addr, count, format
Specifies the starting RAM or EEPROM location of the code that follows.
Repeat block of code a specified number of times.
ORG value RADIX B | BIN | O | OCT |
D | DEC | H | HEX REPT count ENDR
7.3.1 The EQU and = Directives
The EQU (equate) directive defines symbols for constants. See the section entitled “Symbols” for further details. Instead of EQU, you may alternatively use the word GLOBAL; it has the same meaning.
The = (equal) directive defines symbols for constants or assemble-time variables. This directive is similar to EQU except that any symbols created with the = directive can be reassigned new values during assemble-time with additional = directives. See section 7.5 for further details. Instead of an equals sign, you may alternatively use the word SET; it has the same meaning.
7.3.2 The BREAK Directive
The BREAK directive causes a breakpoint to be set at the first line of executable code immediately following it. This is used to set and save a breakpoint in the source code in order to avoid the need to manually set a breakpoint in the Debug window. The syntax of the break directive is:
BREAK breakpoint code
where breakpoint code is the desired line of source code to break on. The BREAK directive is ignored during any operation other than Debug. Only one breakpoint can be defined at a time.
7.3.3 The CASE and NOCASE Directives
The CASE and NOCASE directives specify how to handle the character case (upper or lower) of symbols in source code. The CASE directive will cause all the code below it, up to a NOCASE directive, to be case sensitive. The NOCASE directive will cause all code below it, up to a CASE directive, to be case insensitive. The default is case insensitive. The CASE and NOCASE directives can be used as often as desired and will only affect the code below them.
Using case sensitivity will allow symbols with the same name, but different character cases, to be treated as different symbols. For example:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 47
7 The SASM Assembler
CASE temp EQU $01 Temp EQU $02
The above code would assemble properly and would have two distinct symbols, temp and Temp. NOTE: All directives, instructions and reserved words must be specified in upper case when CASE is active.
Using case sensitive mode can be very tricky, can easily lead to wasted time spent debugging, and is not recommended.
7.3.4 The DEVICE Directive
The DEVICE directive is perhaps the most important directive to appear in source code. This directive specifies the device type, oscillator type, brownout setting and more. The various symbols for specifying these options are listed in Table 6 – SX20/28 DEVICE Settings and Table 7 – SX48/52 DEVICE Settings.
Alternatively you may also use the words FUSES or PROCESSOR instead of DEVICE; they have the same meaning.
The device directive, if supplied, must be the first directive in the code, besides IFDEF or IFNDEF, and must appear before the first instruction. Multiple device lines can be used to accommodate many pa­rameters as long as no conflicting parameters are given. The syntax of the device directive is:
DEVICE setting {,setting…}
The following device lines tell the assembler that the SX chip to be programmed is an SX 20, will use a high speed oscillator, will initiate brown-out at 4.2 volts, runs in turbo mode, and is code protected.
DEVICE SX20AC, OSCHS3 DEVICE BOR42, TURBO, PROTECT
If a setting is not specified, the default is assumed. In this example, the device will also be set for 2-level stack, 6-bit option register, carry bit ignored, no input synching and no watchdog timer, since the opposing settings were not specified. See Table 6 – SX20/28 DEVICE Settings and Table 7 – SX48/52 DEVICE Settings, below, for the defaults.
Page 48 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
Setting
Default
Table 6 - SX20/28 DEVICE Settings
SX20, SX28 DEVICE Settings
SX18/SX18AC/PINS18 SX20/SX20AC/PINS20 SX28/SX28AC/PINS28 BANKS1 BANKS2 BANKS4 BANKS8 OSCHS3 OSCHS2 OSCHS1 OSCXT2 OSCXT1 OSCLP2 OSCLP1 OSCRC OSC4MHZ OSC1MHZ OSC128KHZ OSC32KHZ
IFBD
IRC_CAL
BOR42 BOR26 BOR22 BOROFF
TURBO Specifies turbo mode (1:1 execution) OPTIONX or
STACKX CARRYX ADD and SUB instructions use Carry flag as input** Carry flag ignored SYNC Enable input syncing disabled WATCHDOG Enable the watchdog timer disabled PROTECT Enable code protection disabled
* Any of these OSC settings may be used when an external clock source is connected to OSC1. ** Many instructions are adversely affected by the carry flag when CARRYX is specified. See Appendix B (Chapter 1) and
Appendix C (Chapter 0) for more information.
Specifies the device type SX18
1 page, 1 bank 2 pages, 1 bank 4 pages, 4 banks 4 pages, 8 banks High speed crystal/res., 1MHz…75MHz * High speed crystal/res., 1MHz…50MHz * High speed crystal/res., 1MHz…50MHz * Normal crystal/res., 1MHz…24MHz * Normal crystal/res., 32kHz…10MHz * Low power crystal/res., 32kHz…1MHz * Low power crystal/resonator, 32kHz * External RC circuit Specifies internal oscillator @ 4MHz Specifies internal oscillator @ 1 MHz Specifies internal oscillator @ 128 kHz Specifies internal oscillator @ 32 kHz Disables the internal feedback resistor, i.e. an external feedback resistor is required between the OSC1 and OSC2 pins Specifies the calibration value for the internal RC oscillator, options are IRC_SLOW, IRC_4MHZ and IRC_FAST Brownout to trigger at < 4.2 volts Brownout to trigger at < 2.6 volts Brownout to trigger at < 2.2 volts Disable Brownout reset
Option register is extended to 8 bits, Stack is extended to 8 levels
BANKS8
OSCRC
4 MHz
internal feedback resistor enabled
IRC_SLOW
BOROFF
Turbo off (1:4 execution) Option 6 bits Stack 2 levels
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 49
7 The SASM Assembler
Setting
Default
Table 7 - SX48/52 DEVICE Settings
SX48, SX52 DEVICE Settings
SX48/SX48BD/PINS48 SX52/SX52BD/PINS52 OSCHS3 OSCHS2 OSCHS1 OSCXT2 OSCXT1 OSCLP2 OSCLP1 OSCRC OSC4MHZ OSC1MHZ OSC128KHZ OSC32KHZ
IFBD
XTLBUFD
IRC_CAL
BOR42 BOR26 BOR22 BOROFF CARRYX ADD and SUB instructions use Carry flag as input* Carry flag ignored SYNC Enable input syncing disabled WATCHDOG Enable the watchdog timer disabled PROTECT Enable code protection disabled
SLEEPCLK WDRT60
WDRT960 WDRT006 WDRT184
* Any of these OSC settings may be used when an external clock source is connected to OSC1. ** Many instructions are adversely affected by the carry flag when CARRYX is specified. See Appendix B (Chapter 1) and
Appendix C (Chapter 0) for more information.
Specifies the device type SX18 High speed crystal/res., 1MHz…75MHz *
High speed crystal/res., 1MHz…50MHz * High speed crystal/res., 1MHz…50MHz * Normal crystal/res., 1MHz…24MHz * Normal crystal/res., 32kHz…10MHz * Low power crystal/res., 32kHz…1MHz * Low power crystal/resonator, 32kHz * External RC circuit Specifies internal oscillator @ 4MHz Specifies internal oscillator @ 1 MHz Specifies internal oscillator @ 128 kHz Specifies internal oscillator @ 32 kHz Disables the internal feedback resistor, i.e. an external feedback resistor is required between the OSC1 and OSC2 pins Disables the crystal drive (on OSC2 pin). Use this option to lower power consumption when using a crystal-oscillator-pack connected only to OSC1 pin. Specifies the calibration value for the internal RC oscillator, options are IRC_SLOW, IRC_4MHZ and IRC_FAST Brownout to trigger at < 4.2 volts Brownout to trigger at < 2.6 volts Brownout to trigger at < 2.2 volts Disable Brownout reset
Enable clock generation during sleep mode 60 ms reset delay time 1 s reset delay time
0.25 ms reset delay time 18 ms reset delay time
OSCRC
4 MHz
internal feedback resistor enabled
enabled
IRC_SLOW
BOROFF
disabled
18 ms
Page 50 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.3.5 The DS Directive
The DS (define space) directive increments the location pointer during assembly. This may be used to cause the assembler to arrange sequential RAM assignments (arrays). For example:
ORG $08 Array DS 3 Other DS 2
defines 3 bytes, starting at location 8, for the Array symbol. Array+1 is the second element of the array and array+2 is the third element. The Other symbol’s first and second elements are placed starting with location $0B. Note that no code is generated in the example above.
Instead of the DS, you may alternatively use the words RES or ZERO; they have the same meaning.
7.3.6 The DW Directive
The DW (define word) directive defines 12-bit words in EEPROM. This is used to store a data table in the SX EEPROM space. For example:
DW $FFF, $009, $1A0
stores the values $FFF, $009 and $1A0 into EEPROM starting at the current location. You may also use the DW directive to define a sequence of ASCII characters like in
DW “hello”
This creates a data table in the EEPROM containing the ASCII codes of the characters specified in the string, i.e. $068, $065, $06C, $06C, $06F. See Chapter 10.5 – Creating Tables for more information on using tables.
7.3.7 The END Directive
The END directive indicates the end of the source code in a file. Any text that follows the end directive is ignored by the assembler.
This feature is handy when you want to add any kind of comment text to the end of the source code file without the need to mark each line as a comment.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 51
7 The SASM Assembler
7.3.8 The ERROR Directive
The ERROR directive emits a user-defined message for this source code line. The syntax for the ERROR directive is:
ERROR [P1|2[W|C]]“<string>” During assembly, SASM performs two passes through the source code. The optional first parameter can
be used to control the type of message, and in which pass it shall be emitted. P1 and P2 select the first and second pass; when the parameter is missing, pass 2 is the default. W
defines a warning message, and C defines a comment. When W and C are omitted, the message will be an error. Assembly is stopped on error messages, but it continues on warnings and comments. Errors and warnings are displayed in the status area if the SX-Key software, where comments are only placed in the listing file.
Examples:
ERROR “Message” ; Pass 2 error ERROR P1 “Message” ; Pass 1 error ERROR P1W “Message” ; Pass 1 warning ERROR P1C “Message” ; Pass 1 comment ERROR P2 “Message” ; Pass 2 error (same as the default) ERROR P2W “Message” ; Pass 2 warning ERROR P2C “Message” ; Pass 2 comment
User-defined errors are particularly useful to provide usage checking for complex macros.
7.3.9 The FREQ Directive
The FREQ (frequency) directive is used to set the frequency (in Hz) of the SX-Key’s internal programmable oscillator to be used during debugging. The syntax for the FREQ directive is:
FREQ frequency
Note that frequency can be any number from 400000 to 110000000. Additionally, underscore characters can be used to help make the number more readable, as in 50_000_000, which is 50 MHz.
7.3.10 The __FUSE and __FUSEX Directives
These two directives allow defining explicit expression values for the two SX configuration registers, FUSE and FUSEX (note the two leading underscores in front of the directive names). It is not recommended to use these directives for setting the fuse bits directly. Instead, use the various other directives to configure the SX chip according to the needs of your application.
Page 52 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.3.11 The ID Directive
The ID (identification) directive is used to write up to eight bytes of text into the ID word of the SX chip. This is used to record a version number or other unique identification for the code. This ID word can be read out of the SX chip at any time, regardless of the code protect setting. The line below will write GPXv2.1 into the ID word:
ID ‘GPXv2.1’
7.3.12 The IF…ELSE…ENDIF Directive
The IF...ELSE directive is used to create conditional assembly blocks. A conditional assembly block is source code that is assembled only if the specified condition is true; otherwise, the code block is ignored by the assembler. Conditional assembly allows for easy code customization for multiple applications. For example, it might be necessary to produce a number of related products all based upon the same main source code but each having a small portion of unique code. The syntax for the IF...ELSE directive is:
IF condition codeblock {ELSE codeblock} ENDIF
Note that the ELSE block is optional and the ENDIF is required to end the conditional block. The comparison operators for the condition argument are listed in Table 8 – Comparison Operators, below.
Table 8 – Comparison Operators
Symbol
= Equal
<> Not equal
< Less than
> Greater than <= Less than or equal >= Greater than or equal
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 53
7 The SASM Assembler
The following example demonstrates the use of the IF...ELSE directive.
Delay EQU 10 Choice EQU 1
IF Delay >=9 mov $08, #5 add $09, #%011 ENDIF
IF Choice = 0 mov $0A, #$1B ELSE mov $0A, #$1C ENDIF
The condition for an IF...ELSE directive can contain expressions and multiple conditional statements. Two or more conditional statements may be specified by appending them together with the conditional operators NOT, AND, OR and XOR. For example:
IF choice = 1 AND delay > 9
would assemble the code block following it if choice equals 1 and delay is greater than 9 at assemble time. If the statement or expression evaluates to anything other than zero (0), the condition is true; otherwise, the condition is false.
7.3.13 The IF{N}DEF…ELSE…ENDIF Directives
The IFDEF…ELSE (if defined) and IFNDEF…ELSE (if not defined) directives are very similar to the IF…ELSE directive. The difference is they assemble or prevent assembly of code blocks based on whether a symbol is defined or not. For example:
DriverOn EQU 1 IFDEF DriverOn
{some code block here} ENDIF
would assemble the code block in the IFDEF statement because the DriverOn symbol was defined. If DriverOn was not defined (i.e. line number 1, above, was commented out) the code block would be ig-
nored. Note that SASM considers labels to be defined when there is an assignment using EQU or “=” in the
code before the IF{N}DEF directive, whereas the Parallax Assembler only accepts assignments using EQU.
Page 54 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
With
DriverOn = 1
the Parallax Assembler reports an “Expected a label” error.
7.3.14 The INCLUDE Directive
The INCLUDE directive allows the inclusion of one or more source code files in the main file that contains the include directive. Whenever the assembler processes an include directive, it replaces it with the contents of the file specified. The syntax of the include directive is:
INCLUDE “<File Path>”
<File Path> must either specify a relative or the full file path, including the file name extension. For example, when the include file is located together with the main file in one folder, the directive could be
INCLUDE “SX28Defs.src”
when the include file is located in a sub-folder of the folder where the main file is located, the directive could be
INCLUDE “INCS\SX28Defs.src”
and if the include file is located elsewhere, the directive could be
INCLUDE “D:\SXDev\INCS\ SX28Defs.src”
Please note that the path specification must be specified within quotes, and that the total length of the path specification may not exceed 63 characters.
It is possible to have more than one INCLUDE directive in a program and it is also possible that INCLUDE directives are used in include files, i.e. nesting of include files is allowed at a maximum level of 10.
When nesting include files, take care that files don’t include themselves recursively. Note: Any include files that are open in the editor are not automatically saved when you assemble the
main file. Therefore perform a Save operation on any include files that you have changed before selecting the main file and do an Assemble, Run or Debug operation.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 55
7 The SASM Assembler
7.3.15 The IRC_CAL Directive
This directive specifies the calibration value for the internal RC oscillator. The syntax for the IRC_CAL directive is
IRC_CAL IRC_SLOW | IRC_4MHZ | IRC_FAST
When the options IRC_SLOW or IRC_FAST are specified, the IRCTRIM bits in the FUSEX device configuration register are programmed to the minimum or maximum frequency value. When the option IRC_4MHZ is specified, the SX-Key software performs a calibration procedure whenever a program is downloaded to the SX chip and adjusts the IRCTRIM bits so that the internally generated clock frequency comes close as possible to 4 MHz.
If you don’t intend to use the internal RC oscillator, you should include an IRC_CAL IRC_SLOW or IRC_CAL IRC_FAST directive in your program code in order to de-activate the calibration process, which takes some extra time during downloading code to the SX device.
7.3.16 The LIST Directive
The LIST directive accepts various parameters to control the format of the list file and other assembler option.
The various syntax forms of the LIST directive are:
Page 56 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
Option
Table 9 - LIST Directive Options
LIST C = <columns> Sets the number of columns in the list file (default: no column limit) LIST F = <format>
LIST L = <list>
LIST N = <lines> Sets the number of lines per page in the list file (default: 55)
LIST P = <processor>
LIST Q = <message number>
LIST R = <radix>
LIST W = <0|1|2>
LIST X = <on/off>
Controls the output format of the HEX file – do not use this option because SASM creates the format required by the SX-Key software by default. Controls the list file output (default: NOPAGE): NONE = no list file PAGE = list file with page headers and form feeds, 55 lines/page by default (use LIST N to change the number of lines/page) NOPAGE = continuous list file with no page headers and form feeds
Select the processor type. Use any of the following (default: SX18) SX18, SX18AC, PINS18, SX20, SX20AC, PINS20, SX28, SX28AC, PINS28, SX48, SX48BD, PINS48, SX52, SX52BD, PINS52. It is recommended to use a DEVICE directive instead, to select the processor type. Suppresses the output of the warning with the message number specified (default: output all warnings) Use any of BIN, B, OCT, O, DEC, D, HEX, or H to specify the default radix for numerical values Controls which messages shall be generated: 0 = all messages (comments, warnings, errors) 1 = just warnings and errors 2 = just errors X = ON is a synonym for EXPAND (see section 7.4.5 – The Expand and
X = OFF is a synonym for NOEXPAND
NoExpand Directives)
7.3.17 The LPAGE Directive
The syntax for the LPAGE directive is
LPAGE
This inserts a form feed at this point in the list file. Note that the option LIST L = PAGE should be also active; otherwise, all form feed (including the ones caused by LPAGE directives) will be suppressed.
7.3.18 The ORG (Origin) Directive
The ORG (origin) directive tells the assembler the starting location to use for the following instructions. The syntax for the ORG directive is:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 57
7 The SASM Assembler
ORG location
Note that the ORG directive does not dictate whether the location is in RAM or EEPROM. The assembler simply sets the location pointer as desired and the instructions or directives following the ORG will be processed in relation to this pointer. The ORG directive is used to place data and instructions at specific locations in RAM and E2Flash.
7.3.19 The RADIX Directive
The RADIX directive sets the default for constants. The syntax is:
RADIX = B | BIN | O | OCT | D | DEC | H | HEX
The radix can be set to binary, octal, decimal, or hexadecimal. The default radix is decimal unless modified by a RADIX directive or by LIST R = <radix>.
Here is an example:
ORG 100 ; Sets the origin to 64 hex or 100 decimal (default radix is decimal) RADIX = HEX ORG 100 ; Sets the origin to 100 hex or 256 decimal (radix is hex now)
7.3.20 The REPT Directive
The REPT (repeat) directive is used to indicate that a block of code is to be repeated a specified number of times during assembly. The syntax for the REPT directive is:
REPT count codeblock ENDR
Note that count must be greater than 0 and ENDR is required to end the repeat block. For example:
REPT 3 add $0A, #$01 ENDR
Page 58 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
would result in the source code being expanded to:
add $0A, #$01 add $0A, #$01 add $0A, #$01
during the assembly of the code. Within a repeat block, the percent sign (%) alone may be used to refer to the current iteration (1–n) of
the block during assembly. For example:
REPT 3 add $0A,#% ENDR
would result in:
add $0A, #1 add $0A, #2 add $0A, #3
during the assembly of the code. In other words, during assembly, the first time through the repeat block, the % symbol is equal to 1, the second time through it is equal to 2, etc.
7.3.21 The RESET Directive
The RESET directive specifies the starting address of the code to be executed when a reset condition occurs. The assembler places a ‘Jump to Location’ instruction at the last location in memory to facilitate this. The syntax of the RESET directive is:
RESET location
The location argument must reside within the first page memory.
7.3.22 The SPAC Directive
The Syntax of the SPAC directive is
SPAC <expression>
It inserts the number of blank lines given by <expression> into the list file.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 59
7 The SASM Assembler
7.3.23 The TITLE and STITLE Directives
The TITLE or STITLE directives set up the text to be used in the top line of the list file. The syntax is:
TITLE “<string>” STITLE “<string>”
The text specified with <string> will be repeated on top of each page of the list file, provided the option LIST L=PAGE is active.
7.3.24 The WATCH Directive
The WATCH directive allows the definition of format for viewing and modifying variables at runtime during debug mode. The variable’s bit address, number of bits or bytes to view, and display format may be specified. The syntax for the WATCH directive is:
WATCH symbol{.bit}, count, format
The symbol argument can be a symbol name or register address and can optionally specify a bit address within the symbol. If no bit address is specified, bit 0 is assumed. The count argument indicates the number of bits (1-32) or bytes (1-16) to include in the displayed value. When using the FSTR or ZSTR format, the count is the number of bytes while in all other formats the count is the number of bits. Up to 32 WATCH directives can be specified. Table 10 – WATCH Display Formats, below, lists the available format settings for the WATCH directive.
Table 10 - WATCH Display Formats
Format Operation
UDEC Displays value in unsigned decimal format
SDEC Displays value in signed decimal format
UHEX Displays value in unsigned hexadecimal format
SHEX Displays value in signed hexadecimal format
UBIN Displays value in unsigned binary format
SBIN Displays value in signed binary format FSTR Displays values in fixed-length string format
ZSTR Displays values in zero-terminated format with maximum size
The WATCH directive may be specified anywhere in the source code, below a symbol’s definition; however, it is suggested that it be specified near the top, below where symbols are defined. When code containing one or more WATCH directives is assembled and programmed using Debug mode, a Watch window appears, along with the other debugging windows, to display the results. The Watch window display is updated at the same time the Registers and Code windows are updated. Typically, WATCH directives are used in conjunction with the BREAK directive, however, asynchronous breaks and polls (with the Poll button) may be used to update the display as well.
Page 60 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
The following code snippet is an example of multiple WATCH directives and their output:
LCounter EQU $08 Hcounter EQU $09 Flags EQU $0A String EQU $0B ; (3 chars, $0B - $0D) WATCH LCounter, 16, UDEC WATCH Flags.0, 1, UBIN WATCH Flags.1, 1, UBIN WATCH String, 3, FSTR
Start ; Start of main routine MOV LCounter, #$10 MOV HCounter, #$F0 MOV Flags, #%01 MOV String, #’H’ MOV String+1, #’I’ MOV String+2, #’!’
This code snippet would result in a Watch window similar to Figure 13 – The Watch Window, below:
Figure 13 - The Watch Window
The first variable in the Watch window is created by the WATCH directive on line 5 of the source code. It tells the SX-Key to display a value starting at bit 0 of LCounter (since bit 0 is assumed if no bit address is specified) containing 16 bits and formatted as an unsigned decimal number. Note that although LCounter is only an 8-bit register, the WATCH directive can span multiple registers (from low-byte to high-byte) in order to construct up to a 32-bit value. In this case, LCounter ($08) is the lower 8 bits and HCounter ($09) is the upper 8 bits of the displayed value (61,456 or $F010).
The second and third variables in the Watch window are created by the WATCH directives on lines 6 and 7 of the source code. Both are single bit values, shown in unsigned binary format. The first of these corresponds to Flags’ bit 0 (Flags.0) and the second corresponds to Flags’ bit 1 (Flags.1) as specified by the symbol arguments.
The fourth variable in the Watch window is created by the last WATCH directive. It tells the SX-Key to display a fixed-length string (FSTR) of 3 bytes starting with the String symbol. In this case, ‘HI!’ is displayed.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 61
7 The SASM Assembler
If the ZSTR format is used, the Watch window will display all bytes up to a byte equal to zero, or up to the maximum length (specified by the count argument).
The values in the Watch window can be modified just like registers in the Registers window. See Modifying Registers During Debugging in Chapter 5.1.5 for more information.
7.4 Macros
Macros enhance the capabilities of the assembly language by allowing a user to collect useful sequences of instructions such that they may be inserted in a program easily. These sequences may include parameters that are specified at each invocation to modify the inserted instructions to suit a purpose.
Before a macro can be used, it must be defined. Each macro has a unique name, and may include named formal parameters, unnamed parameters, or no parameters at all.
A macro is defined with the MACRO, EXITM, and ENDM directives. The MACRO directive names the macro and describes its parameters. The ENDM directive marks the end of the definition. An EXITM directive may optionally appear in the macro body to mark a point at which later the use or insertion of the body will be terminated. The macro body consists of all lines extending from the MARCO directive to the next ENDM directive.
Macro definitions may not be nested. That is, it is not possible to write a macro which, when invoked, defines another macro.
7.4.1 The MACRO Directive
The MACRO directive takes one of three forms:
<label> MACRO <formal1>[, <formal2>, …] <label> MACRO <count> <label> MACRO
In all forms, the label names the macro. Macro names must be unique and follow the rules for any symbol name.
In the first form, the macro requires a specific number of parameters, which are given symbolic names. Every invocation must match the number of parameters used in the declaration.
In the second form, requires a specific number of parameters, none of which are named. Use zero for the count to declare a macro which must not take any parameters when invoked. Every invocation must match the specified number of parameters.
In the third form, the macro allows a variable number of parameters, none of which are named. Within the macro body, \0 will be replaced by the number of parameters actually supplied by the invocation.
Page 62 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.4.2 The ENDM Directive
The ENDM directive takes the form:
ENDM
It simply marks the end of the macro declaration.
7.4.3 The EXITM Directive
The EXITM directive takes the form
EXITM
If assembled, it causes an invocation to stop interpolating lines of the macro body at this point. This is sometimes useful when building complex macros. In most cases, the EXITM directive should be placed within an IF, IFDEF, or IFNDEF structure.
7.4.4 The LOCAL Directive
The syntax for the LOCAL directive is
LOCAL <label>[, <label>]…
It declares the labels named after the directive as private symbols. Private symbols are available only inside a macro body. These symbols are private to each invocation of the particular macro and cannot be referenced outside of the macro body.
The private symbol is used within a macro body just like any other label. Each time the macro is invoked, SASM will assign each private symbol a unique name of the form ??0001, ??0002, ??0003, and so forth. The unique name will appear in the listing file in place of all uses of the text of the private symbol.
All LOCAL directives must appear immediately after the MACRO directive and before the first actual line of the macro body.
7.4.5 The EXPAND and NOEXPAND Directives
The EXPAND and NOEXPAND directives specify how to handle macro calls for the purposes of list generation. If a list file is needed that has no macro mnemonics expanded, simply place the noexpand directive above the first macro call. The expand and noexpand directives can be used as often as desired and will only affect the code below them. For example, if source code referenced two macros, M1 and M2, and a list file was needed with only the M1 macro expanded, the expand/noexpand directives might be used as follows:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 63
7 The SASM Assembler
{macro definitions and other code appears above this point}
M1 {arguments here} NOEXPAND
M2 {arguments here} EXPAND
M1 {arguments here}
The above code will result in a list file with the first and last macro calls expanded and the second macro call unexpanded. Note that expand is the default so the expand directive was not used above the first macro call. Additionally, the list file will always show addresses and assembly within a macro regardless of the use of expand and noexpand directives.
7.4.6 Formal Parameters
Formal parameters may be declared by count or by name. If the MACRO directive has one or more names as arguments, those names are the formal parameters. If it has a single constant expression (well­defined in pass 1) that is the exact number of arguments required, the formal parameters are unnamed. If the MACRO directive is not followed by either a constant expression or names of arguments, then any number of arguments may be passed, and the formal parameters are unnamed.
If the formal parameters are named, then any occurrence of a formal parameter name in the macro body will be replaced by the exact text of the actual parameter (defined below) from the macro invocation.
Formal parameter names are case sensitive. That is, a formal parameter named "Foo" on the MACRO directive will be matched by the string "Foo" in the body, not by "foo", "FOO", or any other variations.
Whether or not the formal parameters are named, any occurrence of a backslash ("\") followed by a numeric constant in the current radix will be replaced by the exact text of the corresponding actual parameter from the macro invocation. The sequence "\0" will be replaced by the number of actual parameters available.
In order for the REPT directive to be useful to scan all arguments of a macro, the sequence "\%" will be replaced by the exact text of the actual parameter corresponding to the current iteration of the enclosing REPT directive.
Note that the value after the backslash must be either 0, non-zero and positive, or the percent character. All consecutive digits up to the first non-digit character will be used to form the parameter number.
In all cases, parameter substitution will occur at any point in the input where the reference to a formal parameter is discovered. Parameter names are recognized when delimited by white space, the beginning of a line, a comment or end of line, or one of the macro operators or quote mechanisms described later.
Note that formal parameter substitution does not occur inside of quoted strings or comments.
Page 64 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.4.7 Macro Invocation
Once defined, a macro is used by invoking it with appropriate actual values to be used in place of the formal parameters. When invoked, the macro body is interpolated in place of the invocation, with each reference to a formal parameter replaced by the actual value of that parameter.
The invocation has the form:
<macroname> <parameter1> [, <parameter2> ...]
where macroname must match the name of a previously defined macro, and the number of parameters must agree with that definition.
7.4.8 Actual Values of Parameters
The actual value of a formal parameter is the exact text of the parameter after leading and trailing white space characters are removed. Parameters are separated by commas. The last parameter is terminated by a comment or the end of the line.
If a comma or white space must be passed as part of an actual parameter, then the parameter value may be enclosed in curly braces which will be removed before the value is substituted.
Grouping with curly braces does not prevent any formal parameter (of an enclosing macro) inside the text from being recognized and substituted. Note that ordinary quotes in an actual parameter are preserved, and also prevent formal parameter substitution. See Section 7.4.10 - Quoting on quoting.
7.4.9 Token Pasting
The token pasting operator may be used to concatenate a formal parameter to other text to form a larger token. The token pasting operator effectively works as a zero-width space character which provides an opportunity for the formal parameter reference to be seen, and disappears from the source text for all further processing.
The notation C<token??token> will "paste" the two tokens together into a single token. Either token may be the name of a formal parameter or an index of a parameter in the C<\1> notation which will be substituted by its actual value, or any other text which will be preserved. The resulting text is taken as a single token and must be legal at the point where it appears or a suitable error will occur.
Token pasting is useful for including an actual parameter value as part of an instruction mnemonic or symbol name.
7.4.10 Quoting
On a macro invocation line, curly braces have the effect of collecting all the text they contain as a single actual parameter to the macro. The actual parameter consists of the text enclosed by the braces, which are discarded. Note that if the invocation line is part of the body of a macro definition, any formal parameters in that text will be substituted before the text is used as an actual parameter.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 65
7 The SASM Assembler
Parameter substitution will occur at any point where the reference to a formal parameter can be identified, except within string constants.
The notation "?token" will treat the actual value of the formal parameter named by "token" as if it were a quoted string. This may be useful to use a parameter both as part of a string and as part of an operand to an instruction. This is implemented by quoting the actual value with ASCII unit separator characters ($1f), unless it is already so quoted.
Also, the notation "?( ... )" is available to evaluate an arbitrary well-defined expression and use its value as the text of a single actual parameter. The value is converted to text in the current default radix.
7.4.11 Macro Examples
This section shows some selected examples on how to use macros. Nevertheless, the macro features offered by SASM are so powerful that this section can only cover a subset of what is possible.
7.4.11.1 Simple Macros with no Parameters
CtrlLedOn MACRO clrb rb.0 ENDM
CtrlLEDOff MACRO setb rb.0 ENDM
These two macros simply replace CtrlLEDOn and CtrlLEDOff in the source code by clrb and setb instructions, i.e. the sequence
CtrlLEDOn call Delay CtrlLEDOff
is assembled into
clrb rb.0 call Delay setb rb.0
The advantage of using macros here, is that it is only necessary to modify the macro definitions when another port bit shall be assigned to control the LED later.
Page 66 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
7.4.12 Macros with Formal Parameters by Count
The following is a sample for a macro with one formal parameter:
; Sets the bank appropriately for all types of SX controllers ; _bank macro 1 bank \1 IFDEF SX48_52 IF \1 & %10000000 ; SX48BD and SX52BD bank instruction setb fsr.7 ; modifies FSR bits 4,5 and 6. FSR.7 needs to be set ; by software. ELSE clrb fsr.7 ENDIF ENDIF endm
This macro is useful to replace the BANK instruction in programs that shall be running on SX48/52 devices as well as on “smaller” chips. The BANK instruction only affects FSR bits 4, 5 and 6 but on SX48/42 devices, it is also necessary to set or clear bit 7 in order to switch between the upper and lower banks. So instead of using the BANK instruction to switch between banks, use the _bank macro.
When this macro is used in a program to be run on an SX48/52, it is necessary that the symbol SX48_52 is defined prior to the first invocation of the _bank macro.
The next example is a replacement for the MODE instruction:
; Sets the mode register appropriately for all types of SX controllers ; _mode macro 1 IFDEF SX48_52 mov w, #\1 ; loads the M register correctly for the SX48BD and ; SX52BD mov m, w ELSE mov m, #\1 ; loads the M register correctly for the SX20AC ; and SX28AC ENDIF endm
The MODE instruction has a four bit operand only which is sufficient for SX20/28 devices as they only use four bits of the M register, however, the SX48/52 devices have the added ability of reading and writing some of the port registers, and therefore use five bits in the M register. The MOV M, w instruction modifies all bits of the M register, so this instruction must be used on the SX48/52 to make sure that the M register is written with the correct value. So , instead of using the MODE or MOV M, #<lit> instructions use _mode.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 67
7 The SASM Assembler
When this macro is used in a program to be run on an SX48/52, it is necessary that the symbol SX48_52 is defined prior to the first invocation of the _bank macro.
7.4.13 Macros with Formal Parameters by Name
This is an example for a macro with one named parameter:
delay MACRO cycles IF (cycles > 0) REPT (cycles/3) jmp $+1 ; delay 3 cycles ENDR REPT (cycles//3) nop ; delay 1 cycle ENDR ENDIF ENDM
When invoked with
delay 7
the word “cycles” is replaced by 7 and the macro expands into
IF (7 > 0) REPT (7/3) jmp $+1 ; delay 3 cycles jmp $+1 ; delay 3 cycles ENDR REPT (7//3) nop ; delay 1 cycle ENDR ENDIF
The macro operates by generating as many JMP $+1 instructions as possible to use the bulk of the delay at a cost of one instruction word per three clock cycles then make up the balance with NOP instructions. For example, delay 6 would not generate NOP instructions at all but just two jmp $+1 instructions, where delay 8 would generate two jmp $+1 and two NOP instructions. In case of cycles = 0, no code is generated at all.
7.5 Symbols
Symbols are descriptive names for numeric values. Symbol names can consist of up to 32 alphanumeric and underscore (_) characters and must start with a letter or underscore. SASM expects symbol declarations to start in column 1 of the program line. Symbols for constants are usually defined near the start of assembly source code using the equal directive EQU. For example:
Page 68 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
loop_count EQU 10 index EQU $08
defines the symbol loop_count to be equal to the number 10, and the symbol index to be equal to the hexadecimal number 08. During assembly, everywhere the symbol loop_count appears in the code, the number 10 will be used. Similarly, the hexadecimal number 08 will be used in place of the symbol index during assembly.
Symbols are a great way to define names for registers and constants that would otherwise appear in many places of a program as just non-descriptive numbers. Assembly code that makes ample use of symbols is easier to read and debug and requires fewer comments.
The = directive also assigns values to symbols, but unlike EQU, can reassign values to those symbols. This directive is useful in macros or repeat blocks to create assemble-time variables.
For example:
Count = 0 ORG $20 REPT 5 DW Count + 1 * 2 Count = Count + 3 ENDR
stores the values 2, 8, 14, 20 and 26 in memory locations $20 through $24 at assemble-time.
7.6 Labels
Labels are descriptive names that are given to sections of code. Similar to symbol names, label names can consist of up to 32 alphanumeric and underscore (_) characters and must start with a letter or underscore. SASM expects labels to begin at column 1 of the program line, unless the Local Labels Must Start In Col. 1 checkbox is unchecked in the Configure dialog. Labels are used to direct code execution to specific routines, and are defined simply by specifying the label name before the routine. For example:
Main mov index, #15 jmp main
defines the label Main to point at the first line of code. Later in the program (the second line in this example) to continue execution back at the first line, the jump command is used with the argument Main. This is usually read as, “jump to Main.”
There are three types of labels: global, local, and macro. A global label is one that is unique for the entire length of the code. No two global labels can exist with the same name. A local label is one that is unique for only a portion of the code and must begin with a colon (:). A local label can have the same name as one or more other local labels in a program but they must be separated by at least one global or macro
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 69
7 The SASM Assembler
label. A macro label is the name of a macro block (see the MACRO directive in Section 7.3.15 – The Macro Directive) and is unique.
Depending on the option you have selected in the Configuration window, local labels must begin in text column 1, or may be indented.
No macro label can exist with the same name as another macro or global label. Actually, when a program contains a macro definition, and you use the macro name as a global label by mistake, the assembler would not report an error, but insert the macro code at the location of the “global label”. The following code demonstrates global and local labels.
main mov loop_count, #15 ; initialize loop_count :loop mov $09, #100 ; set some other register djnz loop_count, :loop ; decrement loop_count, ; jump to :loop if not zero continue move loop_count, #50 ; set loop_count to 50 :loop djnz loop_count, :loop ; decrement loop_count, ; jump to :loop if not zero jmp main ;start over
The example above contains two global labels, main and continue, and two local labels, both named :loop. The area between the main and continue global labels is where a local label can exist. Since the djnz in­struction in line 3 references the :loop label, and line 3 is between the global labels main and continue, it will only jump to the :loop label at line 2 and not the :loop label at line 6.
You may also jump to a local label from “outside”. For example, the instruction
jmp continue:loop
elsewhere in the above program example would cause the program execution to be continued with the
djnz loop_count, :loop
instruction. Local and global labels are also allowed within a macro. It is suggested that global labels not be used
within a macro, however, as that would prevent the macro from being called more than once.
7.7 Expressions
Expressions may be used within the arguments of instructions and directives to calculate values at assemble time. The use of expressions helps build more maintainable, easier to understand code. For example, if a program uses values that are all related to the same base number, it makes sense to include an expression crafted from that relationship. If a symbol N is defined as being equal to the base number 2, then N*2+1 and N*3 can be used to derive values related to it; 5 and 6 in this case. At a later time, it might become necessary to adjust the base value to 3 and since expressions were used to derive the related values, only the symbol N needs to be modified.
Page 70 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
All expressions are evaluated at assemble-time only; they are never reevaluated during run-time. This means symbols for unknowns, such as registers (which change at runtime), can not be included inside expressions.
All constants and symbols within expressions may be 32-bit numbers and the result of the expression is a 32-bit number. Since the SX is only an 8-bit processor, care must be taken to extract the appropriate portion of the result for any particular operation. Table 11 – Unary Operators and
Table 12 – Binary Operators describe the available unary and binary operators for use within expres­sions.
Table 11 - Unary Operators
Symbol
|| Absolute value
- Negative ~ Not \ Macro assignment
Table 12 - Binary Operators
Symbol
+ Addition
- Subtraction
* Multiplication
/ Division
// Modulus
& Logical AND
| Logical OR ^ Logical XOR
<< Shift left >> Shift right >< Reverse bits
. Bit address
( ) Sub-expression
Expressions are evaluated strictly from left-to-right, except when parentheses are present. The following code demonstrates some simple expression usage.
loop_count equ 5*3 table ds 5+(2*3) mov loop_count+10/5, #%01101
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 71
7 The SASM Assembler
Data Type
Examp
The second expression, above, will evaluate to 11; the expression within parentheses is evaluated first. The third expression, loop_count+10/5, will evaluate to 5; 15 + 10 = 25 / 5 = 5.
7.8 Data Types
The assembler “understands” four data types: decimal, binary, hexadecimal and ASCII. Table 13 – Data Types, below, describes these data types and their syntax.
For compatibility reasons, the notations xxxxb and xxxxh are also accepted for the binary and hexadecimal data types, respectively. It is suggested that all new SX assembly code use the notation listed in Table 13 – Data Types.
Any numbers that evaluate to a result greater than 32-bits wide will cause an error at assemble time. The largest number allowed is
4_294_967_295 decimal, $FFFF_FFFF hexadecimal, or %1111_1111_1111_1111_1111_1111_1111_1111 binary.
Table 13 - Data Types
Syntax
Decimal Xxxx 1250 Binary %xxxx %01101010 Hexadecimal $xxxx $1AC6 ASCII ‘x’ ‘S’
le
7.9 The __SASM Pre-Defined Constant
SASM has an internal pre-defined constant named
__SASM
(note that there are two leading underscores in the name). This allows the preparation of source code that can contain SASM-specific code, and code that might be relevant for another SX assembler (like the Parallax assembler) by using an IFDEF…ELSE…ENDIF block. Here is an example:
ifdef __SASM DEVICE STACKX IRC_CAL IRC_SLOW else DEVICE STACKX_OPTIONX endif
Page 72 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
When you assemble this code with SASM, the directives in the first (ifdef) block will be read by the assembler, causing the use of an 8-level stack, and the expanded option register, and the RC clock calibration set to slow.
When you use the Parallax Assembler instead, __SASM is not defined, thus the device directive in the lower (else) block will be read, the DEVICE STACKX_OPTIONX directive, which is the correct syntax for the Parallax Assembler to use an 8-level stack, and the expanded option register. This also suppresses the IRC_CAL directive which is not supported by the Parallax Assembler.
7.10 Files created by SASM
When SASM successfully assembles a source code file, it creates the following files, located in the same folder where the source code file resides:
List file (.LST)
Map File (.MAP)
Object file (.OBJ)
In addition, the editor creates or overwrites a backup (.BAK) file when the respective option is set on in the Configure dialog. The backup file is a copy of the previously saved source code file.
All files are named with the associated source code file's name, but with the extensions mentioned above.
The List File contains the original source code plus additional information. Here a part of a list file is shown:
155 =00000000 ISR 156 0000 001C bank Serial 157 158 =00000001 :RS232_Transmit 159 0001 0470 clrb TxDivide.3 160 0002 02B0 inc TxDivide 161 0003 0543 stz 162 0004 0670 snb TxDivide.3 163 0005 0231 test TxCount 164 0006 0643 snz
In the leftmost column you will find the line numbers of the source code file. The next column either contains a value (for lines with labels, EQU, =, ORG, etc. directives), or the instruction address (for lines that evaluate to executable code). When a line contains an instruction, the executable code is shown in the next column to the right of the address.
In the remaining columns, the original source code is shown.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 73
7 The SASM Assembler
At the end of the list file, there is a Cross Reference listing with all symbols used in the program, structured like in the following example:
__SX_FREQ DATA 00989680 0008 __SX_IRC_CAL DATA 00000002 0007 __SX_RESET RESB 00000AA3 0012 _CheckEmergency ADDR 0000033C 0787 ByteCnt VAR 00000097 0124 fsr RESV 00000004 0379
The leftmost column contains the symbol names, followed by the type in the next column (ADDR = label address, DATA = internal values, RESB = reset branch, RESV = reserved variable, VAR = program-defined variable or constant).
The next column shows the values of the symbols, i.e. an address, the constant value, etc., and the rightmost column lists the source code line number where the symbol is defined.
The Map File is not required by the SX-Key software. The Object File contains an image of the generated code as it must be transferred into the SX device’s
program memory during downloads.
7.11 SASM Warning and Error Messages
SASM reports two types of messages during the assembly process: warnings and errors. Warnings are informative message about potential problems with the source code, but they do not halt the assembly or the download process. Errors are critical messages indicating syntactic problems with the source code. Errors prevent assembly from completing successfully and, if invoked, the download process is prevented as well.
While warnings can sometimes provide useful information, many times they can become a nuisance. Therefore, SASM allows warnings to be suppressed with the LIST Q directive. The format is as follows:
LIST Q = {warning number}
where warning number is the actual number displayed together with the warning message when it is not suppressed. For example, you might see a warning similar to the following:
…Line 15, Warning 37, Pass2: Literal truncated to 8 bits
If this warning tells you something you already know, and it is just a nuisance to you, use the warning number (37 in this example) in a LIST Q directive. For example, near the top of the code insert
LIST Q = 37
To suppress multiple warnings, such as #37 and #64, you can use the LIST Q directive in the format shown below:
Page 74 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
Message
Meaning
LIST Q = 37, Q = 64
If you desire to suppress a warning only in a specific area of the code, you can surround the code like this:
LIST Q = 37 mov w, #-200 LIST Q = -37
The minus sign in front of the warning number will toggle it back to an active warning again. The table below summarizes all error and warning messages of SASM:
Table 14 - SASM Error and Warning Messages
SASM Error and Warning Messages
#
1 Bad instruction statement Misspelled instruction or incomplete instruction line E 2 Redefinition of symbol <name> The symbol is already defined with an EQU before E 3 Symbol <name> is not defined The symbol used in a statement is not defined before E 4 Symbol is a reserved word The name you tried to use for a symbol is a reserved word E 5 Missing operand(s) An operand is missing in an expression E 6 Too many operands Too many operands for this expression E 7 Missing file register Specification of a file register is expected E 8 Missing literal A literal was expected E
9 Missing Label A label was expected E 10 Missing right parenthesis A right parenthesis is missing in an expression E 11 Missing expression An expression was expected E 12 Redefinition of MACRO label <name> A macro with this name is already defined E 13 Bad expression An expression is incomplete or incorrect E 14 Bad argument <text> <Text> is not allowed as argument in this expression E 15 Bad MACRO expression A macro expression is incomplete or incorrect E 16 Macro arguments do not match The arguments passed to a macro don’t match the arguments defined E 17 Unmatched MACRO A macro definition is missing an ENDM E 18 Bad IF-ELSE-ENDIF statement Illegal structure of an IF-ELSE-ENDIF E 19 Unmatched ELSE An ELSE without a previous IF was found E 20 Unmatched ENDIF An ENDIF without a previous IF was found E 21 File nesting error - too deep Check for recursive INCLUDES E 22 If.else.endif nesting error - too deep Nesting of IF-ELSE-ENDIF blocks too deep E 23 Invalid digit in numeric constant A digit in a numeric constant is not allowed with this radix E 24 Value is out of range Value too large or too small E 25 Bad radix value Only radix 2, 8, 10, or 16 allowed E 26 Unknown microcontroller type Invalid microcontroller type specified in LIST directive E 27 Unknown output format Bad command line parameter E 28 Unknown listing parameter Bad command line parameter E 29 Bad string syntax A string constant was specified with non-matching quotes E
Overwriting same program
30
counter location
31 Expected an ’=’ sign An equals sign is missing E
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 75
Assembled code expands into an area that has been reserved for other code by an ORG directive
Type
E
7 The SASM Assembler
Message
Meaning
#
32 Unexpected EOF The source code file ends unexpectedly. E 33 Assume value is in HEXADECIMAL No radix specified, hex assumed by default W 34 Token length exceeds limit Internal error E 35 Illegal character - Ignored An illegal character was found and ignored W 36 File register truncated to 5 bits Obsolete message W 37 Literal truncated to 8 bits A literal too large for the target was truncated, e.g. mov fr, 256 W 38 Missing RAM Bank bits Obsolete message E 39 No destination bit Bit move instruction w/o target bit specified E 40 Destination bit can only be 0 or 1 Obsolete message E 41 Bit number out of range A bit number > 7 was specified E
Destination address not in selected
42
page
43 Address exceeds memory limit Address specified targets outside of the available memory E
Address is not within lower half of
44
memory page 45 Label must begin at column 1 An indented label was found E 46 Ignoring unknown directive Unknown directive is ignored during assembly W 47 REPT count exceed limit Only counts up to 254 allowed E 48 File register not in current bank An accessed file register is not within the currently active RAM bank W 49 MODE register value truncated to 4-bits Only the lower 4-bits of value are stored in MODE W 50 Expected a fr.bit operand Bad parameter for a setb/clrb instruction E
Obsolete keyword: <text> for this 51
device 52 Reset address not in page 0
Applied non bitfield operator to a 53
bitfield value
Overriding earlier target device dec­54
laration 55 ERROR <text> Error message generated from the ERROR directive E 56 Source line is too long The length of the source line exceeds 256 characters E
Local symbol <text> expands to more 57
than 130 characters 58 Division by zero Zero-division is in an expression E
59 Literal truncated to 12 bits Only the lower 12-bits of value are used in instruction W 60 Couldn't open file: <name> SASM was unable to open a source file E 61 Couldn't open include file: <name> SASM was unable to open an include file E
Include path and file exceeds 64 62
characters 63 WATCH is missing parameters A WATCH directive was missing some parameters E
IRC_CAL has invalid or missing 64
parameters
No IRC_CAL directive. Default 65
IRC_SLOW being used
No FREQ directive. Default 50 MHz 66
being used
SASM Error and Warning Messages
Type
Destination address for jump or call is outside of currently selected code page
Address of a subroutine call is outside the first half of a program memory page
For example, DEVICE TURBO specified together with DEVICE SX52 W Address specified with RESET is not in the first page of program
memory Illegal bitfield operator W
For example, a DEVICE SX28 follows a DEVICE SX20 directive W
Local symbols are internally stored as “Global:Local”, where “Global” is the name of the previous global symbol, and the total length may not exceed 130 characters.
The full path and filename of an include file was longer than 64 characters
The IRC_CAL directive was incorrectly written E There was no IRC_CAL directive. The default of IRC_SLOW is being
used There was no FREQ directive. The default of 50 MHz is being used W
E
E
E
E
E
W
Page 76 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
7 The SASM Assembler
Message
Meaning
#
Total number of INCLUDE files 67
exceeded 31
Tab expanded list file line too long – 68
truncating
No OSCxxx directive - using default 69
OSCRC 70 USER WARNING: <Message> Warning message generated from the ERROR directive W
E = Error, W = Warning
SASM Error and Warning Messages
Type
No more than 31 include files allowed E SASM internally converts any tabs into spaces, and it does this based
on the tab setting passed to it. With a large number of tabs and large tab setting, it is possible to create an expanded version of a source line that is longer than the maximum length of 256 characters No OSCxxx (e.g. OSCLP!, OSCHS, OSC4MHZ, etc) device directive was provided. The default of OSCRC is being used
E
W
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 77
7 The SASM Assembler
7.12 Reserved Words and Symbols
Table 15 – SASM Reserved Words, below, contains all symbols that are internally defined in SASM, i.e. you may not use any of these words for labels or symbols in your programs. If you try to do that, the assembler will generate an error message.
Table 15 - SASM Reserved Words
__FUSE CSB INC OPTIONX * RESET SX18AC __FUSEX CSBE INCLUDE OR RET SX20 ADD CSE INCSZ ORG RETI SX20AC ADDB CSNE IND OSC1MHZ RETIW SX28 AND DATA INDF OSC32KHZ RETW SX28AC BANK DC IRC_4MHZ OSC4MHZ RL SX48 BANKS1* DEC IRC_CAL OSCHS1 RR SX48BD BANKS2 * DECSZ IRC_FAST OSCHS2 RTCC SX52 BANKS4 * DEVICE IRC_SLOW OSCHS3 SB SX52BD BANKS8 * DJNZ IREAD OSCLP1 SBIN SYNC BOR22 DS JB OSCLP2 SC SZ BOR26 DW JC OSCRC SDEC TEST BOR47 ELSE JMP OSCXT1 SET TITLE BOROFF END JNB OSCXT2 SETB TMR0 BREAK ENDIF JNC PAGE SHEX TO C ENDM JNZ PC SKIP TURBO * CALL ENDR LIST PCL SLEEP UBIN CARRYX EQU LOCAL PINS18 SLEEPCLK ** UDEC CASE ERROR LPAGE PINS20 SNB UHEX CJA EXITM M PINS28 SNC W CJAE EXPAND MACRO PINS48 SNZ WATCH CJB FREQ MODE PINS52 SPAC WDRT006 ** CJBE FSR MOV PROCESSOR STACKX * WDRT184 ** CJE FUSES MOVB PROTECT STATUS WDRT60 ** CJNE GLOBALID MOVSZ RA STC WDRT960 ** CLC ID NOCASE RB STITLE WDT CLR IF NOEXPAND RC STZ XOR CLRB IFBD NOP RD SUB XTLBUFD ** CLZ IFDEF NOT RE SUBB Z CSA IFNDEF OCS128KHZ REPT SWAP ZERO CSAE IJNZ OPTION RES SX18 ZSTR
* SX20/28 only, ** SX48/52 only
Page 78 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
8 The Parallax Assembler
8 The Parallax Assembler
This chapter describes the Parallax assembler. We have added it for completeness, although we strongly recommend using the SASM assembler for new projects. You may use the Parallax assembler to re-build projects that have been developed under a former version of the SX-Key software. You should even consider changing such code so that is assembles under SASM, or both, because there are only a few minor modifications necessary for that purpose (see Chapter 9 – Upgrading Existing Code for SASM).
8.1 The Structure of an SX Assembly Program
The general structure of an assembly program for the Parallax assembler is identical to the one described for SASM in the previous section. Therefore, please refer to Chapter 7.1 – The Structure of an SX Assembly Program for details.
8.2 Assembler Directives
The Parallax assembler supports most of the SASM directives as SASM with the exception of GLOBAL, __FUSE, __FUSEX, FUSES, IRC_CAL, LIST, LOCAL, LPAGE, PROCESSOR, RADIX, RES, SET, SPAC, STITLE, SUBTITLE, TITLE and ZERO, and different options for the DEVICE directive.
Also, the MACRO and ERROR directives are a subset of those in SASM, i.e. some of the options in macro definitions are not supported by the Parallax Assembler.
8.2.1 The Device Directive
Table 16 – Parallax Assembler DEVICE Options, below, lists the available DEVICE directive options.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 79
8 The Parallax Assembler
Setting
Description
XTLBUFD / DRIVEOFF
DRT18MS
DRT60MS
DRT960MS
DRT60US
Device reset timer waits 18 ms
Device reset timer waits 60 ms
Device reset timer waits 960 ms
Device reset timer waits 60 us
SLEEPCLOCK
Clock is enabled during sleep
Table 16 - Parallax Assembler DEVICE Options
SX18/SX18L SX28/SX28L SX48 SX52 OSCHS3/OSCXTMAX OSCHS2/OSCXT5 OSCHS1/OSCXT4 OSCXT2/OSCXT3 OSCXT1 OSCLP2 OSCLP1/OSCXTMIN OSCRC OSC4MHZ OSC1MHZ OSC128KHZ OSC32KHZ
IFBD
BOR42 BOR26 BOR22 TURBO Specifies turbo mode (1:1 execution) 1:4 execution STACKX_OPTIONX Stack is extended to 8 levels and Option register is extended to 8 bits 2 levels/6 bits CARRYX ADD and SUB instructions use Carry flag as input* Carry flag ignored
SYNC Input Syncing enabled WATCHDOG Watchdog Timer enabled Watchdog disabled PROTECT Code Protect enabled
* Many instructions are adversely affected by the carry flag when CARRYX is specified. See Appendix B (chapter 1) and
Appendix C (chapter 0) for more information. Shaded areas indicate SX48/52-only directives.
Specifies the device type SX18
High speed crystal/res., 1MHz…75MHz * High speed crystal/res., 1MHz…50MHz * High speed crystal/res., 1MHz…50MHz * Normal crystal/res., 1MHz…24MHz * Normal crystal/res., 32kHz…10MHz * Low power crystal/res., 32kHz…1MHz * Low power crystal/resonator, 32kHz * External RC circuit Specifies internal oscillator @ 4MHz Specifies internal oscillator @ 1 MHz Specifies internal oscillator @ 128 kHz Specifies internal oscillator @ 32 kHz Disables the internal feedback resistor, i.e. an external feedback resistor is required between the OSC1 and OSC2 pins Disables the crystal drive (on OSC2 pin). Use this option to lower power consumption when using a crystal-oscillator-pack connected only to OSC1 pin.
Brownout to trigger at < 4.2 volts Brownout to trigger at < 2.6 volts Brownout to trigger at < 2.2 volts
Default
OSCHS2
4 MHz
internal feedback
resistor enabled
enabled
No clock during sleep
DRT18MS
no brownout
Input Syncing
disabled
Code Protect
disabled
Page 80 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
8 The Parallax Assembler
Message
8.3 Symbols
Symbols are handled by the Parallax Assembler similar to SASM. Therefore, refer to Chapter 7.5 ­Symbols for more details.
8.4 Labels
Global, local, and macro Labels are also available in the Parallax Assembler. For more details about Labels refer to Chapter 7.6 – Labels.
Unlike SASM, global or local labels in source code for the Parallax Assembler may be indented, i.e. they must not necessarily begin in column 1 of a text line.
8.5 Expressions
Expressions are handled by the Parallax Assembler similar to SASM. Therefore, refer to Chapter 7.7 – Expressions for more details.
8.6 Error Messages
Table 17 – Parallax Assembler Error Messages, below, summarizes the error messages that might be generated by the Parallax Assembler in alphabetic order together with brief explanations in most cases.
Table 17 - Parallax Assembler Error Messages
“=” must be preceded by a variable
“\” only allowed in MACRO definition
CALL must be to first half of page
Constant exceeds 32 bits
Constant exceeds 64 digits Clock frequency must be from 400_000
to 110_000_000 ELSE/ENDIF must be preceded by IF Check for missing or commented-out IF directive above the ELSE/ENDIF. Empty string Look for undefined string within quotes. ENDIF required to end IF block Check for missing or commented-out ENDIF directive below the IF. ENDM required to end MACRO definition ENDR must be preceded by REPT Check for missing or commented-out REPT directive above the ENDR. ENDR required to end REPT block Check for missing or commented-out ENDR directive below the REPT.
EQU must be preceded by a label
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 81
No valid symbol exists to the left of the “=”. Check for mistyped symbol. Watch out for different case when the CASE directive is used. Make sure symbol is not a reserved word.
The macro argument symbol, “\”, is a meaningless character outside of macros. The destination address of the CALL instruction points to the second half of a
page. See section 10.6.2 for more information. The SX-Key assembler can not handle constants whose value is larger than 32 bits or 64 digits. The SX-Key assembler can not handle constants whose value is larger than 32 bits or 64 digits. Designated frequency used in the FREQ directive is outside the range. The SX-Key can only clock the SX chip between 400 KHz and 110 KHz.
Check for missing or commented-out ENDM at the end of a MACRO definition.
A valid symbol must precede the EQU directive. Check for mistyped symbol. Watch out for different case when the CASE directive is used.
8 The Parallax Assembler
Message
Error message contains control characters
Error message exceeds 64 characters EXITM/ENDM must be preceded by
MACRO Expected “++” or “--“ The source operand in a MOVSZ must be preceded by ++ or --. Expected “,” Check for missing arguments on a multi-argument mnemonic. Expected “,” or end-of-line Check for invalid character(s) at the end of the line. Expected a binary operator or “)” Expected a constant Expected a constant, variable, unary operator, or “(“
Expected a DEVICE parameter Expected a label, directive, or
instruction Expected a value from 0 to 64 or end-of­line Expected a value from 1 to 32 The count parameter in the WATCH directive must be in the range of 1 to 32. Expected a terminating quote Look for a string without a terminating quote, or apostrophe. Expected an expression Look for a mnemonic with missing arguments.
Expected end-of-line Expected UDEC, SDEC, UHEX, SHEX,
UBIN, SBIN, FSTR or ZSTR Expected W The W argument is missing in a mnemonic that requires it. Expected WDT The clear-watchdog mnemonic must specify !WDT
Expression is too complex ID cannot exceed 8 characters A maximum of 8 characters are allowed in the ID directive.
ID must be a string of up to 8 characters
Location already contains data
Label is already defined
Limit of 32 nested REPTs exceeded The SX-Key assembler cannot process more than 32 nested REPT blocks. Limit of 100,000 total REPT loops exceeded
List is too large
Macro argument index is out of range Macro argument is not resolvable
MACRO must be preceded by a label A valid symbol must precede the MACRO directive. Check for mistyped symbol.
Error message defined with an ERROR directive must contain printable characters only. Error message defined with an ERROR directive must be 64 characters or less in length. Check for missing or commented-out MACRO directive above the EXITM/ENDM.
Look for mnemonic with bad or missing arguments. Look for incomplete expressions. DEVICE directive contains a missing or invalid parameter. Look for misspellings, commas without trailing parameters, lower case when using CASE directive, etc.
Check for invalid arguments. Check for mistyped mnemonic.
Argument count on macros must be 0 to 64 or not specified.
Look for invalid character or argument at the end-of-line. Look for incomplete expression.
WATCH directive is missing formatter argument.
SX-Key assembler cannot handle the designated expression. Try simplifying the expression if possible.
Make sure to use single quotes, or apostrophes, (‘), before and after the string. Make sure not to input control characters. Assembled instruction overlaps used memory or crossed over last defined page barrier. Can also occur when the RESET directive is specified twice. A symbol, or label, is already defined or is a reserved word. Make sure label’s position is not invalid, such as a label in a REPT block (this would make duplicate labels during the expansion). Make sure label starts with a letter or an underscore (_).
REPT count argument must be in the range 1..100,000. List file generation cannot complete because it is too large. Look for REPT blocks
whose count is high, or whose final size, during assembly, is large. The designated argument index is outside the specified range as set by the macro’s definition.
Page 82 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
8 The Parallax Assembler
Message
Macro stack overflow Macro is too complex; try simplifying it. Nothing to assemble Only one BREAK is allowed The SX chip does not support more than one breakpoint at a time. Port is out of range Redundant DEVICE parameter The parameter specified conflicts with a previously specified device parameter.
REPT count must be greater than 0 RESET address must be on first page The SX chip does not support a reset address outside of page 0.
Symbol exceeds 32 characters
Symbol table full This directive cannot be preceded by a
symbol Undefined Symbol Unrecognized character Use single quotes (‘) instead of double quotes (“).
Variable must be followed by “=” Look for mistyped label.
Must have source code entered or loaded up into the editor before assembling, programming, running or debugging.
Verify the port symbol or address in the mnemonic. See Appendix F for available ports.
All symbols must be 32 characters in length or less and must start with a letter or underscore (_). Too many symbols are defined. Must limit or combine any applicable symbols to assemble properly. Only the ORG, RESET, EQU, =, DS, DW, BREAK, MACRO and END directives can be preceded by a symbol. Symbol is not defined above highlighted line. Check for mistyped symbol. Watch out for different case when the CASE directive is used.
8.7 Data Types
Data types are handled by the Parallax assembler similar to SASM. Therefore, refer to Chapter 7.8 – Data Types for more details.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 83
8 The Parallax Assembler
ADD
DRT60MS *
MOV
RB SZ ADDB
DRT60US *
MOVB
RC
TEST
AND
DRT960MS *
MOVSZ
RD * TIMER_CAPTURE_HIGH *
BANK
DS
NOCASE
RE * TIMER_CAPTURE_LOW *
BOR22
DW
NOEXPAND
REPT
TIMER_COMPARE1_HIGH *
BOR26
END NOP RESET
TIMER_COMPARE1_LOW *
BOR42
ENDM
NOT
RET TIMER_COMPARE2_HIGH *
BREAK
ENDR
OPTION
RETI
TIMER_COMPARE2_LOW *
C
EQU OR RETIW
TIMER_CONTROL_A *
CALL
ERROR
ORG RETP
TIMER_CONTROL_B *
CARRYX
EXITM
OSC128KHZ
RETW
TO
CASE
EXPAND
OSC1MHZ
RL
TRIS CJA FEEDBACKOFF
OSC32KHZ
RR
TURBO
CJAE
FREQ
OSC4MHZ
RTCC
UBIN
CJB FSR OSCHS1
SB
UDEC
CJBE
FSTR
OSCHS2
SBIN
UHEX
CJE ID OSCHS3
SC W
CJNE
IFBD
OSCLP1
SCHMITT
WAKE_EDGE
CLC IJNZ OSCLP2
SDEC
WAKE_ENABLE
CLR INC OSCRC
SET WAKE_PENDING
CLRB
INCSZ
OSCXT1
SETB
WATCH
CLZ IND OSCXT2
SHEX
WATCHDOG
CMP
INDF
OSCXT3
SKIP WDT
COMPARATOR
IND
IRECT
OSCXT4
SLEEP
WKED
CSA IREAD
OSCXT5
SLEEPCLOCK *
WKEN
CSAE
JB
OSCXTMAX
SNB WKPEN
CSB JC OSCXTMIN
SNC WREG
CSBE
JMP PA0 SNZ XOR CSE JNB PA1 ST XTLBUFD
CSNE
JNC PA2 STACKX_OPTIONX **
Z DC
JNZ PAGE
STATUS
ZSTR
DEC JZ PC STC
DECSZ
LEVEL
PD
STZ
DIRECTION
LVL PLP SUB DJNZ
M
PROTECT
SUBB
DRIVEOFF *
MACRO
PULL_UP
SWAP
DRT18MS *
MODE
RA
SYNC
8.8 Reserved Words and Symbols
Table 18 – Parallax Assembler Reserved Words, below, summarizes the words that are reserved in the
Parallax assembler, i.e. you may not use any of these words for a symbol or label.
Table 18 - Parallax Assembler Reserved Words
* = SX48/52 only, ** = SX 20/28 only
Page 84 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
9 Upgrading Existing Code for SASM
9 Upgrading Existing Code for SASM
This chapter describes the most common changes that need to be made to use existing code for the Parallax Assembler with the SASM assembler.
Add an IRC_CAL directive to all existing projects, usually below the DEVICE directives to avoid
the “no IRC_CAL” warning. If you don’t intend to use the internal RC oscillator, use the IRC_SLOW or IRC_FAST rather than the IRC_4MHZ option. The IRC_4MHZ option always increases the download time since the SX-Key needs to run special calibration routines.
Add a FREQ directive to all existing projects to avoid the “no FREQ” warning.
Replace STACKX_OPTIONX by either STACKX or OPTIONX in projects for SX20 or SX28 devices.
No matter which directive you use, both the stack and the option register will be extended to 8-bits; there is no need to specify both. For SX48/52 devices use of STACKX or OPTIONX will cause a warning because these devices have these options always on by default.
Replace FEEDBACKOFF with IFBD when used in the source code.
Replace SLEEPCLOCK with SLEEPCLK when used in source code for the SX48/52.
Replace DRT18MS with WDRT184, DRT960MS with WDRT960, DRT60MS with WDRT60, and
DRT60US with WDRT006 when used in source code for the SX48/52.
Add a LIST Q = 37 directive at the beginning if the source code to suppress “Literal truncated…”
warnings.
Modify any user-defined words that are reserved words in SASM.
Add equates for Parallax reserved words that are not reserved in SASM if necessary.
Add an OSCxxx directive to each project when there is none in the original code. SASM assumes OSCRC by
default where the Parallax Assembler assumes an OSCHS2 instead. The SASM assembler will issue a warning message when it does not find an OSCxxx directive in the source code.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 85
9 Upgrading Existing Code for SASM
Page 86 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
10 SX Special Features and Coding Tips
10.1 Introduction
The SX chip offers many configurable features. This chapter explains how to use many of these features, offers coding tips and demonstrates most topics with sample code. All examples are written for the SX20/28 chips and may need modification for SX48/52 chips.
10.2 Port Configuration and Usage
There are many configuration options for each of the ports on the SX chip as shown in Table 19 – Port Configuration Options, below. The following sections explain how to use the various port
configuration options.
Table 19 - Port Configuration Options
Type Port A Port B Port C* Port D* Port E*
Input/Output X X X X X
Pull-Ups X X X X X
CMOS/TTL X X X X X Schmitt-Trigger X X X X Edge-Interrupts X
Comparator Three Pins
* Port C not available on SX20, Port D and E only available on SX48/52 devices.
To set these functions, a special form of the MOV instruction, called the port configuration instruction, is used to modify the port configuration registers. The syntax of this instruction is:
MOV !port, src
By default, the port configuration instruction writes to the port direction registers, called the tristate registers. To write to other registers, the MODE register must be preset with a specific value. Table 20 – MODE Register Settings lists these values. See chapter 15.4.1 – MODE Register for more information.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 87
10 SX Special Features and Coding Tips
Table 20 - MODE Register Settings
MODE Port A Port B Port C* Port D* Port E*
$0F TRIS_A TRIS_B TRIS_C TRIS_D TRIS_E
$0E PLP_A PLP_B PLP_C PLP_D PLP_E $0D LVL_A LVL_B LVL_C LVL_D LVL_E $0C ST_B ST_C ST_D ST_E $0B WKEN_B $0A WKED_B
$09 Swap W with WKPEN_B
$08 Swap W with COMP_B
$07 - $00 * Port C not available on SX20 devices, Port D and E only available on SX48/52 devices. NOTE: More options exist for the SX48/52 parts. See chapter 15.4.2 for details.
10.2.1 Port Direction
Each of the I/O pins in each of the ports can be configured to an input or output direction by writing to the appropriate tristate register (TRIS_A, TRIS_B, TRIS_C, TRIS_D and TRIS_E). The default I/O pin direction is input. I/O pin direction configuration is usually done once, near the start of code, however, the pin directions can be changed multiple times at any place in the code.
To configure the direction of the I/O pins to inputs or outputs:
1) Set the MODE register to $0F (the default value at startup).
2) Use the port configuration instruction to set the individual directions of each I/O pin within each port. A high bit (1) sets the corresponding pin to input mode and a low bit (0) sets the pin to out­put mode.
The following code snippet demonstrates this:
; Direction Configuration ; MODE $0F ; Set Mode to allow Direction configuration MOV !ra,#%0000 ; Port A bits 0-3 to output MOV !rb,#%11110000 ; Port B bits 4-7 to input, bits 0-3 output MOV !rc,#%00001111 ; Port C bits 4-7 to output, bits 0-3 input
If the logic-level of output pins are expected to begin at a certain state (0 or 1), care should be taken to set the output latch appropriately before setting the pin’s direction to output. Failing to do so may result in a momentary glitch on the pin during initialization. For example, if all output pins were expected to begin in a low state (0), insert the following lines above the previous code snippet:
Page 88 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
; Set output pins low ; MOV ra, #%0000 ; Port A bits 0-3 low MOV rb, #%00000000 ; Port B bits 0-7 low MOV rc, #%00000000 ; Port C bits 0-7 low
10.2.2 Pull-Up Resistors
Every I/O pin has optional internal pull-up resisters that can be configured by writing to the appropriate pull-up register (PLP_A, PLP_B, PLP_C, PLP_D and PLP_E). By configuring pull-up resisters on input pins, the SX chip can be connected directly to open/drain circuitry without the need for external pull-up resisters. The internal pull-up resisters are disabled by default. Pull-up resisters can be activated for all pins, regardless of pin direction but really matter only when the associated pin is set to input mode.
To configure the I/O pins to have internal pull-up resisters:
1) Set the MODE register to $0E (the value for pull-up register configuration).
2) Use the port configuration instruction to set the individual pull-up state of each I/O pin within each port. A high bit (1) disables the pull-up for the corresponding pin and a low bit (0) enables the pull-up resister for a pin.
3) Set I/O pin directions as necessary.
The following code snippet demonstrates this:
; Pull-Up Resistor Configuration ; MODE $0E ; Set Mode for Pull-Up Resistor configuration MOV !ra,#%0000 ; Port A bits 0-3 to pull-ups MOV !rb,#%11110000 ; Port B bits 4-7 normal, bits 0-3 pull-ups MOV !rc,#%00001111 ; Port C bits 4-7 pull-ups, bits 0-3 normal MODE $0F ; Set Mode to allow Direction configuration MOV !ra,#%1111 ; Port A bits 0-3 to input MOV !rb,#%00001111 ; Port B bits 4-7 to output, bits 0-3 input MOV !rc,#%11110000 ; Port C bits 4-7 to input, bits 0-3 output
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 89
10 SX Special Features and Coding Tips
10.2.3 Logic Level
Every I/O pin has selectable logic level control that determines the voltage threshold for a logic level 0 or 1. The default logic level for all I/O pins is TTL but can be modified by writing to the appropriate logic-level register (LVL_A, LVL_B, LVL_C, LVL_D and LVL_E). The logic level can be configured for all pins, regardless of pin direction, but really matters only when the associated pin is set to input mode. By configuring logic levels on input pins, the SX chip can be sensitive to both TTL and CMOS logic thresholds. Figure 14 – TTL and CMOS Levels, below, demonstrates the difference between TTL and CMOS logic levels.
Figure 14 - TTL and CMOS Levels
The logic threshold for TTL is 1.4 volts; a voltage below 1.4 is considered to be a logic 0, while a voltage above is considered to be a logic 1. The logic threshold for CMOS is 50% of Vdd, a voltage below ½ Vdd is considered to be a logic 0, while a voltage above ½ Vdd is considered to be a logic 1.
To configure the I/O pins to use CMOS- or TTL-level logic:
1) Set the MODE register to $0D (the value for logic-level register configuration).
2) Use the port configuration instruction to set the individual logic-level state of each I/O pin within each port. A high bit (1) sets the corresponding pin to TTL-level logic and a low bit (0) sets it to CMOS-level logic.
3) Set I/O pin directions as necessary.
Page 90 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
The following code snippet demonstrates this:
; Logic Level Configuration ; MODE $0D ; Set Mode to Logic Level configuration MOV !ra,#%0000 ; Port A bits 0-3 to CMOS MOV !rb,#%11110000 ; Port B bits 4-7 to TTL, bits 0-3 CMOS MOV !rc,#%00001111 ; Port C bits 4-7 to CMOS, bits 0-3 TTL MODE $0F ; Set Mode to allow Direction configuration MOV !ra,#%1100 ; Port A bits 0-1 to output, bits 2-3 input MOV !rb,#%10110011 ; Port B bits 2,3,6 to output, all others input MOV !rc,#%11011110 ; Port C bits 0,5 to output, all others input
10.2.4 Schmitt-Trigger
Every I/O pin in port B through port E can be set to normal or Schmitt-Trigger input. This can be configured by writing to the appropriate Schmitt-Trigger register (ST_B, ST_C, ST_D and ST_E). The I/O pins are set to normal input mode by default. Schmitt-Trigger mode can be activated for all pins, regardless of pin direction but really matter only when the associated pin is set to input mode. By configuring Schmitt-Trigger mode on input pins, the SX chip can be less sensitive to minor noise on the input pins. , below, details the characteristics of Schmitt-Trigger inputs.
Figure 15 - Schmitt Trigger Characteristics
Schmitt-Trigger inputs are conditioned with a large area of hysteresis. The threshold for a logic 0 is 15% of Vdd and the threshold for a logic 1 is 85% of Vdd. The input pin defaults to an unknown state until the initial voltage crosses a logic 0 or logic 1 boundary. A voltage must cross above 85% of Vdd to be interpreted as a logic 1 and must cross below 15% of Vdd to be interpreted as a logic 0. If the voltage transitions somewhere between the two thresholds, the interpreted logic state remains the same as the previous state.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 91
10 SX Special Features and Coding Tips
To configure the I/O pins to Schmitt-Trigger input:
1) Set the MODE register to $0C (the value for Schmitt-Trigger register configuration).
2) Use the port configuration instruction to set the individual Schmitt-Trigger state of each I/O pin within each port. A high bit (1) sets the corresponding pin to normal and a low bit (0) sets it to Schmitt-Trigger.
3) Set I/O pin directions as necessary.
The following code snippet demonstrates this:
; Schmitt-Trigger Configuration ; MODE $0C ; Set Mode to Schmitt Trigger configuration MOV !rb,#%11110000 ; Port B bits 4-7 to normal, bits 0-3 to S.T. MOV !rc,#%00001111 ; Port C bits 4-7 to S.T., bits 0-3 normal MODE $0F ; Set Mode to allow Direction configuration MOV !rb,#%10110011 ; Port B bits 2,3,6 to output, all others input MOV !rc,#%11011110 ; Port C bits 0,5 to output, all others input
10.2.5 Edge Detection
Every I/O pin in port B can be set to detect logic level transitions (rising edge or falling edge). This can be configured by writing to the Edge Selection register (WKED_B) and detected by monitoring the Pending register (WKPEN_B). The I/O pins are set to detect falling edge transitions by default. By configuring edge detection on input pins, the SX chip can set the pin’s associated bit in the Pending register when the desired edge arrives. The Pending register bits will never be cleared by the SX alone; the running program is responsible for doing so. This means, if a desired edge is detected, the flag indicating this will remain set until the program has time to attend to it. This feature can be used by the SX program for signals that need attention, but not necessarily immediately.
To configure the I/O pins for edge detection:
1) Set the MODE register to $0A (the value for Edge Detect register configuration).
2) Use the port configuration instruction to set the individual edge to detect on each I/O pin. A high bit (1) sets the corresponding pin to falling-edge detection and a low bit (0) sets it to rising-edge detection.
3) Set I/O pin directions as necessary.
Page 92 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
The following code snippet demonstrates this:
; Edge Detection Configuration ; Start MODE $0A ; Set Mode to allow Edge configuration MOV !rb,#%11111111 ; Port B bits 0-7 to falling edge MODE $0F ; Set Mode to allow Direction configuration MOV !rb,#%11111111 ; Port B bits 0-7 to input
Main MODE $09 ; Set Mode for Pending register check MOV !rb,#%00000000 ; This line moves WKPND_B to W and ; writes all zeros to WKPND_B JMP Main ; At this point, W should be checked for
; high bits, indicating a falling ; edge occurred
The following are points to remember with edge detection:
The edge detection feature is always enabled and the Pending register is always updated even if the
SX program does not configure or use it.
It is up to the SX program to clear the bits of the Pending register when detection of a future
transition is desired. The MOV !rb, #%00000000 instruction effectively clears all bits of the Pending register at the same time that it stores the current edge detection status in W.
If the SX program is designed to handle only one edge detection event at a time (on two or more
pins), it will be necessary to get the status (as shown above), clear only the bit being attended to and move the modified status back to the Pending register.
An edge detection event will not wake up the SX chip from a SLEEP mode unless the Wake-Up
Enable mode is also set. See below for more information.
10.2.6 Wakeup (Interrupt) on Edge Detection
Every I/O pin in port B can be set to cause an interrupt upon logic level transitions (rising edge or falling edge). By configuring interrupts on input pins, the SX chip can respond to signal changes in a quick and deterministic fashion. In addition, an interrupt of this sort will wake up the SX chip from a SLEEP state. This can be configured by writing to the Edge Selection register (WKED_B) and the Wake­Up Enable register (WKEN_B) and detected by monitoring the Pending register (WKPEN_B) in the interrupt routine. The I/O pins have interrupts disabled and are set to detect falling edge transitions by default.
As with edge selection, the Pending register bits will never be cleared by the SX alone; the running program is responsible for doing so. This means if a desired edge is detected, the interrupt will occur
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 93
10 SX Special Features and Coding Tips
and the flag indicating this will remain set until the program clears it. Additional transitions on that pin will not cause interrupts until the associated bit in the Pending register is cleared.
To configure the I/O pins for wake-up (interrupt) edge detection:
1) Set I/O pin edge detection as desired. (See Edge Detection, above, for more information).
2) Set the MODE register to $0B (the value for Wake-Up Enable register configuration).
3) Use the port configuration instruction to enable the individual pins for wake-up interrupts. A high bit (1) disables interrupts and a low bit (0) enables interrupts.
4) Set I/O pin directions as necessary.
5) Clear the Pending register to enable new interrupts.
The following code snippet demonstrates this:
RESET Start Interrupt ; Interrupt routine (must be at address $0)
ORG $0 MODE $09 ; Set Mode for Pending register MOV !rb,%00000000 ; Clear Pending/get current status in W RETI ; rest of interrupt routine goes here
; Wake-Up Edge Detection Configuration ; Start MODE $0A ; Set Mode to allow Edge configuration MOV !rb,#%11111111 ; Port B bits 0-7 to falling edge MODE $0B ; Set Mode to allow Wake-Up configuration MOV !rb#%11110000 ; Port B bits 4-7 to normal, 0-3 to Wake-Up MODE $0F ; Set Mode to allow Direction configuration MOV !rb,#%11111111 ; Port B bits 0-7 to input MODE $09 ; Set Mode for Pending register MOV !rb,%00000000 ; Clear register to allow new interrupts Main NOP ; rest of main routine goes here JMP Main
Page 94 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
The following are points to remember with Wake-Up Interrupts:
The interrupt routine must be located starting at address $0 in the SX program.
It is up to the SX program to clear the bits of the Pending register when future interrupts on that pin
are desired. This should normally be done as part of the interrupt routine. The MOV !rb, #%00000000 instruction effectively clears all bits of the Pending register at the same time that it stores the current edge detection status in W.
The SX chip will activate the interrupt routine exactly 5 clock cycles in Turbo mode or exactly 10
clock cycles in compatible mode after a Wake-Up Edge Detection event occurs. This deterministic feature allows for nearly jitter-free interrupt response. Latency may vary by as much as +1 instruction cycle when interrupting on external asynchronous events, thus a high clock speed may be necessary to lessen the effects.
If multiple interrupt pins are required, the SX chip may not be able to properly process them in
certain situations. See Interrupts, below, for more information.
An edge-detection interrupt event will wake up the SX chip from a SLEEP mode.
10.2.7 Comparator
I/O pins 0 through 2 in port B can be set for comparator operation. This can be configured by writing to the EN and OE bits of the Comparator register (CMP_B) and monitored by reading the RES bit. The comparator mode is disabled by default. Comparator mode can be activated for all three pins, regardless of pin direction, but really matters only when pin 1 and 2 are set to input mode (pin 0 can optionally be set to output the comparative result). By configuring Comparator mode, the SX chip can quickly determine logical differences between two signals and even indicate those differences for external circuitry.
When comparator mode is activated, the RES bit in the Comparator register indicates the result of the compare. A high bit (1) indicates the voltage on pin 2 is higher than that of pin 1, a low bit (0) indicates the voltage on pin 2 is lower than that of pin 1. If the OE bit (Output Enable) of the Comparator register is cleared, output pin 0 of port B reflects the state of the RES bit.
To configure port B I/O pins 0 though 2 for Comparator mode:
1) Set the MODE register to $08 (the value for Comparator register configuration).
2) Use the port configuration instruction to enable the Comparator and, optionally, the result output on pin 0.
3) Set I/O pin directions appropriately.
The following code snippet demonstrates this:
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 95
10 SX Special Features and Coding Tips
; Comparator Configuration
; MODE $08 ; Set Mode to Comparator configuration MOV !rb,#%00000000 ; Enable comparator and result output MODE $0F ; Set Mode to allow Direction configuration MOV !rb,#%11111110 ; Port B bits 1-7 to input, bit 0 to input Main MODE $08 MOV !rb,#$00 JMP Main ; Here, bit 0 of W holds result of compare
The following are points to remember with Comparator mode:
Port B I/O pins 1 and 2 are the comparator inputs and I/O pin 0 is, optionally, the comparator
result output.
Port B I/O pin 0 may be used as a normal I/O pin by setting the OE bit of the Comparator register.
The comparator is independent of the clock source and thus will operate even if the SX chip is
halted or in SLEEP mode. To avoid spurious current draw during SLEEP mode, disable the comparator.
10.3 The SX48/52 Multi-Function Timers
In addition to the standard timers (RTCC and watchdog), the SX48/52 devices come with two Multi­Function Timers T1 and T2. These timers are useful to replace a software solution for generating PWM signals, counting events, and generating longer time delays.
Each timer comes with a free-running 16-bit counter. At reset, the counters are initialized with $0000, and then, they start continuously counting upwards. The counters can either be clocked from the system clock (through an 8-bit prescaler), or from an external transition at the external clock pin. This input can be configured to sense positive, or negative transitions.
Each counter has associated 16-bit capture and comparison registers. As an option, various events can be used to trigger an interrupt, or to generate an output signal.
Page 96 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
Compare
16-Bit Comparison R2
16-Bit Comparison Register
Output (RB6/RC2)
External Clock
Capture
The block diagram in Figure 16 – SX48/52 Multi-Function Timers, below, shows the components of one timer:
Figure 16 - SX48/52 Multi-Function Timers
Interrupt
Capture 2 (RB5/RC1)
R1
Interrup
System Clock
8-Bit Prescaler
Multiplexer
Capture 1 (RB4/RC0)
or Capture Register (2)
16-Bit Comparator
16-Bit Counter
16-Bit Capture Register (1)
Registers R1, R2 and the capture registers can be accessed by mov !rb, w (Timer1), or mov !rc, w (Timer2) instructions. The remaining registers cannot be accessed via software.
Timer 1 shares its input and output lines with the Port B pins 4...7, and Timer 2 shares its input and output lines with the Port C pins 0...3. If a timer is active, those pins can no longer used for "regular" I/O purposes.
10.3.1 PWM Mode
In this mode, the timer generates a square wave signal with programmable frequency, and duty cycle. For this purpose, the contents of the two comparison registers determine for how long the signal is high, and low.
The 16-bit counter starts with a value of 0, and keeps incrementing until it has reached the value of R1. Then, the counter is reset to 0, the output is toggled, and (if enabled) an interrupt is generated.
Next, the counter keeps incrementing until it reaches the value of R2. Again, the counter is reset to 0, the output signal is toggled, and an interrupt is triggered (if enabled).
These two steps are repeated continuously. The contents of R1 and R2 determine the frequency and the duty cycle of the generated output signal. When R1 and R2 contain the same value, a square wave with a duty cycle of 50% is generated. In order to generate a signal with a constant frequency, and a varying
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 97
10 SX Special Features and Coding Tips
duty cycle, the sum R1+R2 must remain constant, i.e. to change the duty cycle, increase the value of one register, and decrease the value of the other register by the same amount.
In PWM mode, the 16-bit counter is clocked through the prescaler from the system clock. The prescaler can be set to divide-by factors from 1 to 256 in steps of powers of two.
10.3.2 Software Timer Mode
This mode is similar to the PWM mode with the difference that the output signal is not toggled. Instead, the application program must react on the interrupts that indicate a match between the counter and R1, or between the counter and R2. An additional interrupt is generated when the counter overflows from $ffff to $0000.
10.3.3 External Event Counter
Again, this mode is similar to the PWM mode, but here, the 16-bit counter is clocked from an external signal instead of the system clock. The external input can be configured in order to have positive or negative transitions increment the counter.
10.3.4 Capture/Compare Mode
In this mode, the 16-bit counter is clocked by the prescaled system clock and it keeps incrementing without being reset. A valid transition at one of the two inputs causes the current counter contents to be stored in the associated capture register. This makes it easy to determine the time difference between two external events.
In addition, the counter contents are continuously compared against the contents of register R1. If both are equal, an interrupt is generated (if enabled), and the output signal is toggled. Unlike the PWM mode, the counter is not reset in this case, it keeps incrementing.
In order to obtain a fixed period between the interrupts and output toggles, the ISR must load a new value into R1 whenever an interrupt is triggered.
The two inputs Capture 1 and Capture 2, can be configured to trigger on positive or negative transi­tions.
Capture register 1 is a separate register dedicated to capture the counter contents only, where Register R2 is used for the capture register 2.
As an option, each capture event can also issue an interrupt and various flags allow the ISR to determine the cause of the interrupt.
In addition, a 16-bit counter overflow can also trigger an interrupt, and set a flag. This is important when the time between two external events is long enough to allow for one or more counter overflows. If the ISR keeps track of the number of overflows, it is possible to calculate the time elapsed between two external events.
Page 98 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
10 SX Special Features and Coding Tips
10.4 All About Interrupts
The SX20/28 chip allows for up to nine sources of interrupts; eight external and one internal. The SX48/52 chip allows for up to 17 sources of interrupts; 10 external and one internal. Any or all of the port B I/O pins can be configured as external interrupts. See Chapter 10.2.6 – Wakeup (Interrupt) on Edge Detection for information on configuring external interrupts. The internal interrupt can be configured to occur upon a rollover condition within the Real Time Clock Counter (RTCC) register. A special return-from-interrupt command may also be used to adjust the value of the RTCC to cause interrupts to occur at a specific time interval. See section 10.4.1 for more information.
In addition to the interrupts supported by the SX20/28, with the SX48/52 devices, six different internal interrupts can be configured for the Timer 1 and Timer 2 overflow and R1/R2 counter comparison reg­isters.
These interrupt options can be very powerful features but can also cause havoc if not configured or understood properly. If using interrupts of any kind is desired, the following items should be reviewed.
Interrupt Vector: The interrupt vector in the SX chip points to address $0 and is not configurable. The
interrupt routine must reside at location $0 to be properly executed upon an interrupt event.
Auto Interrupt Disable: As soon as an interrupt occurs, additional interrupts are automatically
ignored by the SX chip until the interrupt routine is completed. This prevents the interrupt routine from being interrupted and prevents the loss of return vector data. This is also one of the most important considerations when working with interrupts; you can not immediately (without jitter) process more than one interrupt at a time.
Note: Should additional interrupts occur, the SX chip does not automatically queue up interrupts for future processing. See Interrupt Queuing, below, for more information.
Latency Delays: When an interrupt occurs, there is a latency delay before the interrupt routine is
actually activated. For the internal RTCC rollover, this latency is exactly 3 clock cycles in Turbo mode and 8 clock cycles in Compatible mode. For the external interrupts, the latency delay is exactly 5 clock cycles in Turbo mode and 10 clock cycles in Compatible mode. Latency may vary by as much as +1 instruction cycle when interrupting on external asynchronous events, thus a high clock speed may be necessary to lessen the effects.
Interrupt Routine Size: Normally it is a requirement for an application to process every interrupt
without missing any. To ensure this happens, the longest path through the interrupt routine must take less time than the shortest possible delay between interrupts.
Interrupt Queuing: If an external interrupt occurs during the interrupt routine, the pending register
will be updated but the trigger will be ignored unless interrupts had first been turned off at the beginning of the routine and turned on again at the end. This also requires that the new interrupt doesn’t occur before interrupts are turned off in the interrupt routine. If there is a possibility of extra interrupts occurring before they can be disabled, the SX will miss those interrupt triggers.
SX-Key/Blitz Development System Manual 2.0 Parallax, Inc. Page 99
10 SX Special Features and Coding Tips
Multiple Interrupts: Using more than one interrupt, such as multiple external interrupts or both
RTCC and external interrupts, can result in missed or, at best, jittery interrupt handling should one occur during the processing of another.
Clearing Pending Bits: When handling external interrupts, the interrupt routine should clear at least
one pending register bit. The bit that is cleared should represent the interrupt being handled in or­der for the next interrupt to trigger.
Debugging Interrupts: The SX chip may act strangely while debugging code that contains interrupts.
The SX chip may or may not enter the RTCC interrupt routine (and will never enter a MIWU interrupt) while using the Step or Walk functions. This is due to the SX chip giving higher priority to the SX-Key than its internal interrupt flags. If interrupt code needs to be debugged or verified, place a
BREAK directive, or a breakpoint, in an appropriate place within the interrupt routine and use the Run or Poll functions.
10.4.1 RTCC Rollover Interrupts
The SX chip can be set to cause an interrupt upon rollover of the Real Time Clock Counter (RTCC). By configuring an interrupt on RTCC rollover, the SX chip can perform an operation at a predefined time interval in a deterministic fashion. This can be configured by setting the STACKX or OPTIONX fuse (in the DEVICE directive) and writing to the RTI, RTS and RTE bits of the Option register (OPTION). The RTCC rollover interrupt is disabled by default.
To configure the RTCC rollover interrupt:
1) Set the STACKX or OPTIONX fuse in the DEVICE line.
2) Write to the RTI, RTS and RTE bits of the OPTION register to enable RTCC interrupts. For RTI, a high bit (1) disables RTCC rollover interrupts and a low bit (0) enables RTCC rollover interrupts. For RTS, a high bit (1) selects incrementing RTCC on internal clock cycle and a low bit (0) increments RTCC on the RTCC pin transitions. For RTE, a high bit (1) selects incrementing on low­to-high transition and a low bit (0) increments on a high-to-low transition.
Page 100 SX-Key/Blitz Development System Manual 2.0 Parallax, Inc.
Loading...