You are on page 1of 209

USER MANUAL

for the

SYSTEM51

PAS51W version 6.5

Release 20000111.

Copyright (C) 1991..2000 by KSC Software Systems.


All rights reserved.
IMPORTANT NOTICE!!

The SYSTEM51 is a copyrighted program system. It is prohibited to


copy this manual in parts or in the whole on any medium in any way
without the written permission of the author. It is prohibited too, to
make unauthorized copies of the programs, consult your "License
Agreement". If you discover any error in the system, please report it to
KSC Software Systems, as this may be of mutual interest.

KSC Software Systems,


Rosenstandsvej 6 B,
DK-2920 Charlottenlund,
Denmark.
Fax (Int. 45) 39 64 39 53

Copyright (C) 1991..2000 by KSC Software Systems.


All rights reserved.

Intel is a registered trademark of Intel corporation.


PLM is a registered trademark of Intel corporation.
Windows and Windows95 are registered trademarks of Microsoft
corporation.
TABLE OF CONTENTS

P A R T I , The IDE

1. INTRODUCTION. 1

1.1 Installation. 3

1.2 Starting the system 4

2. TUTORIALS. 7

2.1 A simple tutorial. 7

3. THE SYSTEM51 INTEGRATED ENVIRONMENT12

3.1 The SYSTEM51 pull down menus. 12

3.2 The File Menu 13

3.3 The Edit Menu 15

3.4 The Search Menu 16

3.5 The View Menu 16

3.6 The Compiler Menu 17

3.7 The Run Menu 20

3.8 The Options Menu 22

4. EDITOR 22

4.1 The Window Menu 25

4.2 The Help Menu 25

i
4.3 Moving around in the editor screen. 26

4.4 Entering or deleting editor text. 28

4.5 Block Commands. 29

4.6 Finding or/and Replacing Text Strings. 30

5. THE PAS51W COMPILER 32

6. THE INTEGRATED SIMULATOR 34

7. THE (EXTERNAL) SIMULATOR. 36

7.1 Overview of the Simulator. 36

7.2 The Simulator Screen. 37

7.3 Running the Simulator by hotkeys and pull down menus. 38


7.3.1 The Simulator File Menu. 39
7.3.2 The View Menu. 43
7.3.3 The Watch menu 48
7.3.4 The Display/Set Menu 49
7.3.5 The RUN Menu 50
7.3.6 The Macros Menu 55
7.3.7 The Search Menu 55
7.3.8 The Window Menu 56
7.3.9 The Help Menu 56
7.3.10 The accellerator shortcut keys 56

7.4 Running the simulator by commands. 57


7.4.1 Command Language. 57
7.4.2 Format of expressions. 57

7.5 The Commands. 59


7.5.1 Examining or Modifying Memory or Registers. 59
7.5.2 Run and Trace Commands. 62
7.5.3 SETUP Commands. 63
7.5.4 DOMAIN command. 63
ii
7.5.5 LOAD command. 64
7.5.6 LIST command. 64
7.5.7 WRITE command. 65
7.5.8 READ command. 65
7.5.9 CALC command. 66
7.5.10 DEF command. 66
7.5.11 Structured commands inside macros. 67
7.5.12 Executing macros. 68
7.5.13 INCLUDE command. 69
7.5.14 PUT command. 69
7.5.15 MACRO command. 70
7.5.16 PAUSE command. 70
7.5.17 ECHO command. 70
7.5.18 REM command. 71

7.6 Organization and limitations. 71

8. EMULATORS. 72

9. THE ASSEMBLER ASM51. 73

9.1 Examples of assembler programs. 78

10. THE LINKER LINK51. 84

11. THE SFR COMPILER. 85

iii
P A R T I I, The PAS51 Language

12. THE LANGUAGE. 89

13. BASIC SYMBOLS. 90

14. BASIC DATA STRUCTURING. 92


14.1.1 Unstructured types. 92
14.1.2 Structured types. 93

14.2 Variables. 96
14.2.1 Predefined variables. 97
14.2.2 Absolute placed Variables. 97

14.3 Named Constants. 98

15. STATEMENT PART. 99

15.1 Assignment. 99

15.2 Input and Output. 100

15.3 Sequential composition. 105

15.4 Selection. 106


15.4.1 If Statement. 106
15.4.2 Case Statement. 107

15.5 Repetition. 108


15.5.1 While Statement. 108
15.5.2 Repeat Statement. 108
15.5.3 For Statement. 109

iv
15.6 The WITH statement. 110

15.7 Combining the Constructs. 111

15.8 Embedded code. 112

15.9 GOTO in PAS51. 113

16. EXPRESSIONS AND CALCULATION RULES.113

17. PROCEDURES AND FUNCTIONS. 117

17.1 Procedures. 117

17.2 Value parameters. 118

17.3 Variable Parameters. 119

17.4 Functions. 120

17.5 Scopes and Recursivity. 121


17.5.1 Scopes. 121
17.5.2 Recursivity. 122

17.6 Predefined procedures and functions. 123

17.7 The general typecast function. 128

17.8 Interrupt procedures. 129

17.9 External procedures. 134

18. POINTERS. 135

18.1 Pascal-like Use of Pointers. 136

18.2 C or PL/M type Use of Pointers. 137

19. SET. 137


v
20. OBJECTS. 139

20.1 Inheritance. 140

20.2 Virtual Methods. 141

20.3 Constructors and the extension to New. 142

20.4 Destructors. 143

20.5 The SELF variable. 144

20.6 Parameters to Methods. 144

20.7 Examples on Objects. 145

21. PROVISIONS FOR CONCURRENCY. 150

21.1 Newprocess and Transfer. 150

21.2 Signal and Waits. 154

22. SEPARATELY COMPILED UNITS. 157

23. BANK SWITCHING WHEN CODE >64 K BYTES.


161

24. COMPILER DIRECTIVES. 164

25. OPTIMIZATION OF INTERNAL RAM SPACE.171

25.1 Using the (*$O Directive. 172

26. RUNTIME ERROR HANDLING. 173

27. COMPILE TIME ERROR HANDLING. 173


vi
27.1 Errors. 173

27.2 Stack Overflow Warning. 173

28. INFORMATION ON MEMORY AND REGISTER


USE AND PARAMETER PASSING. 174

28.1 Register Use. 174

28.2 Parameter Passing. 174

28.3 Memory organization. 175


28.3.1 Internal Data Memory. 175
28.3.2 External Data Memory. 177
28.3.3 Program Memory. 177

29. INTERFACING PASCAL WITH ASSEMBLER OR


SYS51C 177

vii
viii
SYSTEM51 1
________________________________________________________

P A R T I , The SYSTEM51.

1. Introduction.

Congratulations with your new system. KSC Software Systems is


convinced that you will enjoy the powerfulness and user friendliness of
this system. The SYSTEM51 is a complete software development
system for program development for the INTEL 8051 family of
microcontrollers. It contains a complete high level language compiler,
based on the language Pascal, an integrated text editor, an assembler, a
relocating linker, and a simulator with unique high level language
window facilities. As an option, you may order the DEBUG51 emulator
package which include facilities for In Circuit Debugging your 8051
CPU family based printed circuit board.

This version will need Microsoft Windows, WIN95 or newer.

The high level language PAS51W, supplied with the system, contains
an almost complete implementation of Pascal by Wirth with a few
exceptions and several additions to make it compatible with Borland
Delphi and Pascal version 7.0 and also several additions especially
suited for the INTEL 8051 microcontroller used in embedded systems.
You may for instance directly access all the special registers, ports,
interrupt services and bits of the chip by their INTEL-defined names.

The PAS51W compiler is a 1-pass compiler (on the source level) which
may directly generate

1) A relocatable .OBJ file with symbol and line/state-


ment information;

2) An INTEL compatible .ASM file intermixed with


high level language (HLL) statements as
comments.
2 SYSTEM51
________________________________________________________

3) (optionally) an INTEL .LST file of the compi-


lation.

When choosing Build, Make or Make/Run from the menu of the


system, the linker will automatically be called, and the output from that
will be:

1) An Intel compatible absolute file in AOMF


format .A51

2) An Intel compatible binary hex file .HEX

3) A map file .MAP

4) (Optionally) An IAR UBROF compatible file


.UBR

Only the necessary parts of the runtime package will automatically be


linked. When compiling single module programs, the size of the
runtime package linked will be from a few bytes by simple programs
and up to 4 kilobytes by programs utilizing all the different, advanced
features of the PAS51W. The compiler generates very optimized code
in both speed and program size compared to competing compilers.
Compared to assembler, you will find a factor of about 2 to 1 in code
size and execution time.

When you encounter a programming error in your PAS51W source text


while executing it, you can switch directly back into the integrated text
editor, and the cursor will point automatically to the erroneous point in
your text.

When using the simulator or the DEBUG51, you will see the
corresponding high level source in a window, and you will be able to
modify and examine memory, and register and flag values and to step
on HLL statements.
PAS51 3
________________________________________________________

The SYSTEM51 may also be upgraded to include the KSC Software


Systems SYS51C compiler for the 8051 microprocessors, which
produces object code which can be intermixed with PAS51W modules
and assembler modules. In this case, the main menu of the SYSTEM51
will automatically find out which compiler to use.

1.1 Installation.

The system(s) are delivered to you on two or more diskettes. Most of the
content is packed. To install the software, you must have 1) Microsoft
Windows 95 or later installed on your computer, 1) the necessary
diskette(s) available, 3) necessary free space available on your harddisk
(about 2mbytes depending on the configuration, and 4) the installation
company name and corresponding control code available.

For installation, please place the (1.) diskette in the A: drive, go to the

Windows control panel, and click on Add/Remove Programs.


4 SYSTEM51
________________________________________________________

Fig. 1

An INSTALLSHIELD® sequence should then be started, see fig 1;


follow the instructions.

Fig. 2
When fig. 2, inserting company name and serial number shows up, you
must carefully enter the information send to you. Please enter exactly as
stated. The serial number to enter is identical to the control code of the
form 123456-7890. (Your serial number is in fact the number after the
‘-’). Do not try to "improve" or correct spelling errors in company name
and control code. The code is your and our guarantee for no illegal
copying or use of the system.

1.2 Starting the system


PAS51 5
________________________________________________________

The system is normally intended for use with the integrated Windows
IDE. However, for your convienience, you have the choice of using the
command line versions of the compiler (PASCAL.EXE), the assembler
(ASM51.EXE) and the linker (LINK51.EXE). You may also use the
simulator (SIM51.EXE) stand alone. However, you can’t move those
programs to other computers without re-installing the full system there.

When using the Integrated Development Environment (IDE)


SYS51W.EXE, you will get a screen picture with a caption, initially
SYS51W, but after you have choosen a project, SYS51W - project.PAS,
a MENU bar, a speed button area, and an area, where editor windows
and a message window will be placed when load a file.

From the menu bar pull down menus, the speed buttons or by using the
accelerator keys, you can invoke the compiler, the integrated or stand
alone simulator, optionally the debugger, the linker or the assembler,
and you can open or change editing windows or set options.
6 SYSTEM51
________________________________________________________

In the editing window(s), you will be able to enter and/or modify source
texts, or any other texts including the generated .LST, .ASM, and
.MAP files. When the compiler or the assembler meets an error, you
will return to the erroneous point in this window.

In the "Messages" window, you will see different messages from


compilers, linkers, simulators, and other called programs.
PAS51 7
________________________________________________________

2. Tutorials.

If you prefer to learn about the system by systematically reading about


the different parts of the system, you may prefer to transfer to chapter 3.
If you prefer learning by doing, you probably will stay here.

2.1 A simple tutorial.

In this tutorial, you will try to write on your screen the message "Hello,
SingleChip" 4 times.

If you have finished installation as described in chapter 1, you are ready


to try the system.

Click on the SYS51W icon

You will now see the system picture with a menu and speedbutton bar
above, and an empty area below (if this is the first time you start the
system).

Press the File menu, select ‘Project Main File’ and click on
HELLO.PAS

In an edit window you should see the .PAS program HELLO.PAS. Try
to move a little around in the text using the cursor keys, Home, End,
PgUp, PgDn, ^PgDn (Ctrl key pressed at the same time as PgDn) and
^PgUp.
8 SYSTEM51
________________________________________________________

Also try to press F1, on line help.

We will now deliberately make an error. Press ^PgUp to go to the top of


the file. Then press ^F and the text Find What: will show up in a Find
box. Enter the text "counte", then press the ‘Find Next’ button The
cursor will now be placed at int counter; press ‘Find Next’ again. The
text at the cursor now shows while counter<4 do . Press the ESCAPE
key to remove the Find box. Enter key "x" to make an error.

Now enter Alt-C and a new window, a so called pull down menu will
come down; click the mouse on Make, press M or the cursor down key
and then Enter ; the compiler will be invoked, open a window called
"Messages", but after a while it will discover the error in the source file,
give an error message in the message window, and bring you back
again in the editor with the cursor on xcounter. Press <Del> and the
text will again be while counter< .

Perhaps you saw in the pull down menu that the hot key for making
was F12; therefore press F12. Now the compiler will compile to an end
and the linker will take over. The message

Linking complete, no errors.

will appear in the messages window. You are back in the main system
menu.

Check that Run/SetUp is set to (Integrated Simulator).


Then press the speedbutton with the running man or use the Run/Run
(see setup) pull down menu (pressing Alt-R then R) . Your IDE
program in the PC will now simulate a 8051 CPU by being able to
execute the translated program.
PAS51 9
________________________________________________________

The figure shows the result of the run of the integrated simulator.The
“Messages” window

Instead you could have envoked the stand alone simulator from the
IDE, press Shift-F9.

The simulator screen that comes up, looks very much like the main
screen with a MENU line above,a speed button area and a source text
window.

In the source text window you will see the HELLO.PAS program with
some numbers to the left. Those are program addresses. You will use
those later on.

First we will just try to run the program. Press the function key F9, run.

A run window will pop up, and the output from the program, 4 times
the text "Hello, Singlechip" will appear in that window.
The text "RUNNING" will be shown at the right in buttom field. Press
ESC to return to the "READY" mode.

We will now analyze the execution of this program in more details.


First, press ^F2 to reset the program counter to the start of the program,
i.e. code address 0.
10 SYSTEM51
________________________________________________________

Bring the variable "counter" into the watch window. This may be done
in the following way: Search for the word counter as in the editor: ^F
counter Enter. Then ^F7. A watch input dialog box with the input line
showing "counter" will come up. The "counter" will come up because
the cursor pointed there. Now type Enter, and the watch contains the
counter variable and its value in decimal and hex notations, together
with its address. As we have already run the program, this value will be
4. Because it is declared as an (16 bit) int, it is shown as 16 bit. To see
both HELLO.PAS and the watch window, press the tile speed button (2
white squares above each other) or Alt W/T, to tile the windows.

Press ^F9, animate. You will see the program stepping while the watch
will be updated.

Perhaps it all happened too fast, so let us use a breakpoint instead. Press
^F2 again.

Press F3 (search for next) until the cursor points to counter:=counter+1.


Press F2 to set a breakpoint on that statement. The statement will now
be shown in red (if you have a color screen) to show that a breakpoint is
set there. You might also have pressed the breakpoint speed button

instead.

Press F9 or , run, 5 times. The first four times, the simulator will
stop at the statement, writeln( will write its message, and the watch will
be updated. The fifth time the simulator will continue as the for
statement is passed. Press ESC to stop running the program.

Leave the simulator by entering Alt-F4. You now returned to the


SYS51W IDE.

At the time you compiled the program without errors, several files were
generated: HELLO.OBJ, HELLO.ASM, and HELLO.A51 which are
used by the simulator, as well as the files HELLO.MAP and
HELLO.HEX.

We will now look at the files HELLO.ASM and HELLO.MAP.


PAS51 11
________________________________________________________

Press Alt-F/P. Select File Type .ASM, HELLO.ASM, and you will open
a new editor window showing the newly generated HELLO.ASM file.

Move a little around in it and study the generated .ASM code mixed
with .PAS statements as comments. Normally, this is the only purpose
of this file.

Press F9 or the Make speed button, and the message

The Make Facility found No File to Recompile or Relink

will probably appear in the "messages" window. This is so because the


file HELLO.PAS or any option were not modified since the last
compilation, and no changes occured in the file HELLO.OBJ since the
last linking.

Running this program on a real 8051 target depends on the type of


hardware you have got. But the following procedure may be used: use
the HELLO.HEX file to program an (E)EPROM. If you have a
Sunshine EPROM programmer, remember to use the HEXOBJ
program to convert the .HEX file to an image obj file. Connect the
SBUF serial channel on your PC board with a terminal, for instance the
PC. If it is the PC,activate the terminal driver in Windows. Press
RESET on your target, and 4 lines of Hello SingleChip will appear.
12 SYSTEM51
________________________________________________________

3. The SYSTEM51 Integrated Environment

In the figure, you see a typical picture of the SYS51W integrated


environment (the IDE). In this Windows environment, you will work
on developing your 8051 programs. From here, you may enter your
source code, envoke the compiler, the linker, the assembler , the
simulator, the debugger or your emulator. If you are used to other
Windows MDI programs, you will soon feel confortable using this IDE.
In the following, it will be explained in more detail. When working in
the system, you may also call online help, either by F1, help depending
on where you are in the moment, or ^F1, which will search for the
keyword below the editor carét.

In the following we will explain the facilities in mode detail.

3.1 The SYSTEM51 pull down menus.

To activate one of the items in the pull down menus, do one of the
following:
PAS51 13
________________________________________________________

A) Click the menu with the mouse to pull down the menu. Then
click the item with the mouse.

B) Press Alt-<l>, where <l> is the underlined letter in that


menu.
Then press the letter underlined at the item.

C) Press Alt-<l>, where <l> is the highlighted letter in that


menu.
Move the bar up or down with the cursor keys to the wanted
item, then press Enter.

The possible pull down menus are:

The menu bar is the uppermost line on your screen. You may go there
by pressing F10, clicking the mouse or pressing Alt-the highlighted
letter.

From the menu bar, you may pull down menus for almost any purpose.
To activate an item from a pull down menu, click the item with the
mouse, press the highlighted letter or move the bar up and down with
the cursor keys and then press Enter.

The menu looks like the following when you have an editor window
open:

File Edit Search View Compiler Tools Options Window Help

The single menu points will be explained in the following:

3.2 The File Menu


14 SYSTEM51
________________________________________________________

There are different sorts of files in the system as explained in the


following.

To manipulate them, choose one of the following menu points:

New File... Open an edit window for untitled file


Open File... Ctrl-O Open an existing file
Reopen File Submenu of earlier opened files
Project Main File... Open file as main file in project
Reopen Project Submenu of earlier opened as project
Clear Project No specific project
Save Ctrl-S Save the file to disk
Save as... Save the file to disk with a different name
-------
Print Ctrl-P Print 1 copy without asking for details
Print... Print after asking for details
-------
Exit Alt-X Close the IDE and exit

The name of the project main file will be shown on the system caption
as SYS51W-name.PAS

The relevant file types are:

name.PAS (PAS51 source file)


name.C (SYS51C source file)
name.H (SYS51C header file)
name.MOD (MOD251 source file)
name.DEF (MOD251 definition file)
name.ASM (assembler source file, either generated by a compiler or
written by you)
---
name.KPR (project file, text, but normally maintained by the system)
name.OBJ (compiled relocatable file, output from compiler or
assembler)
name.A51 (absolute file including debug information for the simulator
or the debugger.)
name.MAP (map file of linking process)
PAS51 15
________________________________________________________

name.LST (list file from assembler) extension name may be changed


in Options
name.LIS (list file from compiler) extension name may be changed in
Options
name.HEX (Intel .hex file for PROM-programmers PROM simulators,
et cetera)
name.IN4 (configuration file (text) for the system programs)
name.DSK (window configuration information)

Speed buttons may be used for some of the file operations:

which from left to right are: Load File, Save, Exit and Print (without
questions)

3.3 The Edit Menu

Undelete Ctrl+Z Reestablish changes in a single line


-----------------------------
Cut Ctrl+X Moves marked block to clipboard
Copy Ctrl+C Copy marked block to clipboard
Paste Ctrl+V Insert clipboard at cáret.
Clear Deletes marked block
Select all Mark whole file

Undelete will only restore a modified line, if you haven't moved away
from that line.

Some speed buttons may be used instead of those 4 menu points:

From left to right: Undelete, Cut, Copy, Paste


16 SYSTEM51
________________________________________________________

3.4 The Search Menu

Find Ctrl+F Open Find dialog box


Find Next F3 Find next appearence of same text
Replace Ctrl F3 Find and replace dialog.

Some speed buttons may be used instead of those 3 menu points:

From left to right: Find, Find Next, Replace

3.5 The View Menu


With this menu, you may make visible two bars with quick tools
available.

The menu looks like this:

View Toolbar If checked, the toolbar is available


View Tabbar If checked, a tabbed toolbar is available

The toolbar contains icons as mentioned above.

With the tabbed toolbar, you get available different tools to simplify
your PAS51 programming.
PAS51 17
________________________________________________________

On left tab “Language Templates”, two combo boxes appear. Choose a


programming template; double click the mouse to insert the template
into the editor text.
On the left but one tab “Built-ins”, three combo boxes will be available.
In the left one, all accessible SFR registers will be selectable. Again
double click to insert into the editor text. In the middle box, all
available interrupts will be selectable. Double click the mouse to insert
an interrupt procedure template into the editor text. The content of
those boxes will depend on the actually selected target.
On the right but one tab “Variables/Functions/Types, the combobox
“User defined names (last make/build)” will initially be empty, but after
a build, all names you have defined in the program(s) included in the
project will be available. As before, a mouse double click will insert the
selected name into the editor text.

3.6 The Compiler Menu

With this menu, you may invoke other parts of this integrated system,
like the compiler, the linker or the assembler

The menu looks like this:

Compile Ctrl+F9
Make F12
Build Ctrl+F12
Make/Run Ctrl+F8
Assemble Ctrl+A
Link Ctrl+L

The single points described in more detail:

Compile Ctrl-F9
18 SYSTEM51
________________________________________________________

Pressing Compile|Compile, Ctrl-F9 or the above button will


cause a compilation of the file in the foreground. The selected
compiler will be that of the Hll-extension of the file (.C for
SYS51C, .PAS for PAS51 and .MOD for Modula2). In case of
errors you will return to the editor state with the cursor pointing to
the errouneous point.

No automatic linking takes place. (This is in contrast to the DOS


versions of SYSTEM51)

If you want the whole project compiled and linked, choose Make
or Build.

Make F12.

When pressing F12, a conditional compilation / linking will take place


based on the content of the file Project N)ame.KPR. In case this file do
not exist, a minimum file of that name will be created. In case the
Project N)ame is empty, the name of the foreground file will be used.

The conditions for recompilation / linking is that the resulting file type
(.OBJ for compilation, .A51 and .HEX for linking) is older than any of
the source files or the date of the relevant opT)ions settings.

For the format of the .KPR file, see Project

Build

By choosing Build or pressing the above button, all the files


described in your Project will be re-compiled; if no errors occur,
PAS51 19
________________________________________________________

the different files will then be linked; if, however, errors occur,
you will be taken to the point of the first error.

The ASM51 Assembler

This assembler is invoked from here in the following


way:

If you are in the simulator or DEBUG51, return to the IDE before


further commands.

If you are in the IDE, press Ctrl-A. The file Project N)ame.ASM will
then be assembled. If errors occur, you will return to the erroneous
point in the assembler source.

After assembling, you must link your program(s) before running them.

The Linker Ctrl-L

A dialog box will appear when this is selected. A combo-box offers you
some suggestions of linkings, but you may enter your own.

PAS51W files need to be inked with the runtime library files FP51
(only if real or longint is used), PL51 and IODRIVER. In case that you
use the Siemens 80C517 or 80C537, the runtime library files are
FP517, PL517 and IODRIVER, in case you use the small Philips
80C748..80C751, only use PL751.

SYS51CW files need to be linked with the runtime library files FPC51
(only if float or long is used), CL51 and IODRIVER. In case that you
use the Siemens 80C517 or 80C537, the runtime library files are
FPC517, CL517 and IODRIVER. In case of Reentrancy mode 2, the
files are FPCR51, CLR51 and IODRIVER.
20 SYSTEM51
________________________________________________________

IODRIVER must be the last file linked to a HLL program, as this


decides the placement of the stack.

If you want a .HEX file generated, you must include a -H

3.7 The Run Menu

Run (see setup) F9 Executes the project


Step (internal) F7 Executes one statement
Step Over F8 Executes one statement, where
a call is considered one statement
Stop (internal) Stop the integrated simulator
Toggle Breakpoint F5 Sets / resets a breakpoint at
the cursor position
-----------------------
Simulate (external) Calls the external simulator
Debug (external) Calls some external debugger or emulator
Terminal Calls a COMx port terminal program
SetUp... Open a setup dialog box

There are several different methods the execute and debug your Pascal
program.

1) Integrated with the IDE there is a limited simulator available. You


may run a .PAS program continuously or to breakpoint met, single
step or step into one single statement. In a small popped up window,
you are able to watch some essential data. The integrated simulator
function will be described in chapter 6.

2) A stand alone full high and low level simulator may be invoked
from the IDE or from a command line. See chapter 7.

3) A stand alone debugger (optional), full high and low level, may be
invoked from the IDE or from a command line. Described in a
separate manual.
PAS51 21
________________________________________________________

4) Your own emulator may be invoked from the IDE.

With the help of the setup dialog box, you are able to setup certain
information about your tools for executing and debugging your
programs.

In the text field, named "Name of RUN program", you may select the
name of the program, to which the RUN button and F9 will respond. To
select the integrated simulator as the choosen tool , choose (Integrated
simulator), to select the stand alone simulator, choose SIM51 (stand
alone), to select DEBUG51 as the tool, choose DEBUG51W, and to
select other tools such as a 3. party emulator, write its name in the Run
select box.

In the "Name of emulator" text field, you enter the name of your
debugging or emulating tool, ex. DEBUG51W

If DEBUG51W is your selection, you may setup communication speed


and channel in the "Emulator Parameters" text field. If any 3. party
emulator, enter the necessary parameters for that emulator here.

Example for DEBUG51W: COM2:19200

In the ‘Terminal parameters’ box, you set up the parameters for


communication using the ‘Terminal window’. The only available COM
ports and baud rates are those shown in the combobox selections.
22 SYSTEM51
________________________________________________________

3.8 The Options Menu

4 different sub-menus, Target, Editor, Compiler and Directories, leads


you to different parts of a multi-page options setting dialog box. The 4
pages in the dialog box are

Target

With this Combo box, placed on page “Target” in the Options dialog
box, you set the target processor, for which you want to generate code.

If your target isn’t in the list, you may use the SFR2SFB compiler
system to include it.

4. Editor

On this page, you may set different options in the text editing windows.
You may set the width of a tab (default 8), if entering a tab should
generate spaces or a character in the source code (default spaces), if
your editor is in insert or overwrite mode (default insert, shown in the
panel below left).

You may also select if you want your C or Pascal-code shown in online
syntax colours (default on, select which colours and styles for each
lexical type in "syntax").

Autoindent (default on) means that new lines will automatically indent
to the 1. non-blank position in the line above. Improves structured
program entry.

By pressing the Font button, a standard window Font dialog box will
appear. You may change font type and size. We recommend that you
choose a fixed width font like “Courier New”, as this will give the best
results. Do not set font color here.
PAS51 23
________________________________________________________

By pressing the “Syntax Colors” button, a pop-up menu gives you the
choice of selecting colors for different types of tokens:

Normal colors
Reserved words
Identifiers
Comments
Strings

We strongly recommend you to use at least a different shape / color for


comments, as many bugs, not recognized by the compilers, may be
visually found in this way.

If you want the others to be different or not is a question of taste.

To disable the facility,click the "Syntax Display" checkbox.

Compiler

On this page, you set different options concerning the compiler(s) that
you use in your system. In the “Current Compiler” combo-box, you may
see the current selected compiler and available ones, you may also set
another one, but normally, you will not get anything out of that, as the
system itself will decide which one from the file extension.

In the Conditional edit box you set default compiler conditionals. In the
Directives edit box, you set default compiler conditionals.

The “Strictly Intel AOMF” check-box defines whether the generated


debug information should contain only such information, defined in the
INTEL AOMF51 format, or should contain extended information used
by the DEBUG51 and the SYSTEM51 simulator.

The .ASM and .HEX generation check-boxes allow you to taylor which
files should be generated as does the Generate IAR UBROF box,
whereas the 2 Ext of File boxes allow you to taylor names of extensions.
24 SYSTEM51
________________________________________________________

Regarding the "Strictly Intel AOMF" checkbox, it decides whether


.OBJ and .A51 debug information should be extended for use with
SIMUW, DEBUG51W, EXUM51 or SYMCONV or limited (“Strictly
Intel”) to follow the Intel standard as used in many 3. party emulators,
but do not include any type information. Because the IAR UBROF
format contains such information, we recommend you to use tat instead
if your emulator is able to use that.

Regarding the "Generate .ASM" checkbox, the only reason to exclude


this may be to avoid this disk space and time consuming facility.

Regarding the "Generate .HEX" check box, you should include this
facility when you need to program an EPROM with the final code. Most
EPROM-Programmers need that.

As different 3. party emulators need different extensions of different


files, the extensions of the list files from the compiler and the assembler
may be taylored.

Directories

This page sets up some default search path directories.

For those familiar with the DOS versions of SYSTEM51, the directory
structure is rather different in this Windows version. All outputs from
the different compilers, linkers and assemblers will go to the project
directory, which is the directory where the project source file resides. If
you want the Make facility to be able to recompile/reassemble
programs, all those source files must also reside in the project directory.

The “Default Project Directory” is, if containing a non-zero string, the


suggested directory that will show up in the project file open box. If you
choose a project file in a different directory, this directory will not be
hanged.
PAS51 25
________________________________________________________

In the source “include files directories” edit line, you may enter several
disks and pathes of directories where you have placed your include
source files.The pathes must be separated by ";". As the different
programs start searching in the project directory, you need not mention
that.

In the user .OBJ files directories dialog box, you may enter disks and
pathes of several directories where you want your linker to search for
the .OBJ files. The different pathes must be separated by ";".

The linker will look for its .OBJ files 1.) in the project directory. 2.) in
the
directory where your system files are placed. 3.) in these directories.

4.1 The Window Menu

The sub-menu points are:

Tile Look at all opened windows at the same time


Cascade Look at opened windows as a 3-D row.
----------
Messages Open / Goto the "Messages" window.

4.2 The Help Menu

The single menu points are:

Contents F1
Topic Search Ctrl+F1
How to use Help
--------------------
About...

This standard Windows menu may envoke the Windows standard help
system in different ways, or you may see in the about box, details about
your installation of the SYSTEM51.
26 SYSTEM51
________________________________________________________

F1 will also bring you to the help system, as will the speed button.
Depending on where you are in the menues of dialog boxes, the default
help item will change.

When pointing to a word in the editor text, Topic search pressing


Ctrl+F1 will start searching for this word.

4.3 Moving around in the editor screen.

Summary:
-> Move cursor 1 position right.
<- Move cursor 1 position left.
^ Move cursor 1 position up.
v Move cursor 1 position down.
^-> Move cursor word right.
^<- Move cursor word left.
Home Move cursor to start of line.
End Move cursor to end of (nonblank) line.
PgUp Move cursor one screen page up.
PgDn Move cursor one screen page down.
^PgUp Move cursor to start of text.
^PgDn Move cursor to end of text.
^QG Move to line #n (given in a dialog box)
^Qn Move to marker #n.

Using keystrokes:

To move 1 position up, down, left or right, use the cursor pad
keys.

To move to the left or right end of the current line, press Home
or End, alternatively press ^Q^S or ^Q^D.

If you want to see whats beyond the rightmost shown coloumb, just
scroll the
PAS51 27
________________________________________________________

picture horisontally.

To move one screen page up or down, press the PgUp or PgDn.

To move to the start or end of the text file, press ^PgUp or ^PgDn,
alternatively press ^Q^R or ^Q^C.

To go to a specific line number (from the beginning of the file),


use ^QG<line number>.

To go to a previously marked marker, press ^Qn, where n is a digit ‘0’


to ‘9’

You could alternatively click the mouse on where you want to go if


inside the current window, or click on the scrollbars with the mouse to
get the wanted text point into sight.
28 SYSTEM51
________________________________________________________

4.4 Entering or deleting editor text.

Summary of keystrokes:

<letter> Inserted or overwrite existing.


DEL or ^G Delete at cursor
^H or Backspace Delete left of cursor
^N Insert line
Enter New line
^Y Delete line
^T Delete word
^QY Delete rest of line
^Z Restore line
----
Ins or Alt-P/E/I Toggle insert
Alt-P/E/T Toggle tabs Generate Spaces
Alt-P/E/A Toggle autoindent

When you press any visible character, it will be inserted at the cursor
position, and the rest of the line will move to the right. To enter
characters with a nonvisible ASCII value ( < 32 ), press ^P and the
character. It will then be shown on the screen in a different colour or
intensity.

When entering Return, a new line will be generated, and you will move
to the start of the new line. If you instead press ^N, a new line will be
generated, but you will remain on the previous one.

A special feature, the auto indent feature, allows you to beautify your C
or Pascal programs. If you press Return or ^N, and the old line contains
1 or more spaces to the left, the same number of spaces will
automatically be inserted. The indent feature may be disabled / enabled
by pressing Alt-P/E/A.
PAS51 29
________________________________________________________

Tabs in the text will move the cursor to the next by-n-dividable position
on the line. The value of a toggle switch, tabson, will decide whether
the character ^I or spaces will be inserted in the text buffer. This toggle
switch may be changed in the Options menu, where also the value of n
may be set.

To delete a character, press ^G or DEL to delete the character at the


current cursor position, or press ^H or BackSpace to delete the
character to the left of the cursor position.

To delete a whole line, press ^Y. To delete to the end of the line, use
^QY. To delete the word at the right of the cursor position, use ^T.

A changed line may be restored by pressing Ctrl+Z

4.5 Block Commands.

Keystroke command summary:

New style:
Shift curser moves: Mark block
^X Cut marked block to clipboard
^C Copy marked block to clipboard
^V Paste from clipboard

Old style:
^KB Start of block.
^KK End of block.
^KT Mark word.
^KL Mark line
^KH Hide block.
^KC Copy marked block to cursor position. Also put it into the clip-
board.
^KP Print marked block.
^KR Read file into cursor position.
30 SYSTEM51
________________________________________________________

^KW Write marked block to file.


^KI Indent marked block
^KU Unindent marked block
^Kn Set marker #n ('0' - '9')

Mouse command summary:

Start of block: Push down the left button on mouse at position.


End of block: Release mouse button at position.
Others: Push one of the following buttons:

Cut
Copy
Paste

Descriptions:

With the help of those commands, you are able to mark a


whole block of text, and then delete it or to move or copy it
to somewhere else in the text buffer.

The ^K^P will print the marked block on your printer.

^K^R will read a disk file into the text whereas ^K^W will
write the marked block to a disk file.

4.6 Finding or/and Replacing Text Strings.

Keystroke command summary:

^QF Find string.


^QA Find/Replace string.
F3 Find (Find/Replace) next.
^QG Goto line.
PAS51 31
________________________________________________________

Mouse command summary:

Press one of the following buttons:

Find
Find/Replace next
Replace

Or pull down the Search menu and click on the item.

Detailed:

By pressing Search|Find or ^F, a dialog box 'Find:' will appear.


You may now enter any text string you want to
find in the text. You may also set/reset some options, shown in the
dialog box.
When you press the Enter key or "OK" button, the
editor will search for that string from the current position
of the cursor to the end of the text buffer. If found, the cursor
will be placed at the found position, if not, a "Not found" message box
will appear. Touch Enter or click on "OK".

By pressing Search|Replace or ^QA, you may enter a text string that


may later be found in the text buffer and replaced.
According to your selected options, you may chose not to
replace the actual string.

If the editor is called from the system menu, both find and
find/replace will offer you the values poined at as suggestions: you
may use those values by typing Enter or click; you may edit the values
by moving the arrows and then typing; or you may just start typing a
new value.

By pressing F3 or Search|Next, the search for the string last entered


by ^F or ^QA will be repeated. This may be done after other
commands.
32 SYSTEM51
________________________________________________________

5. The PAS51W Compiler

The language PAS51W is described in details in Part II of this manual


and will not be explained further in this part.

Here the operation of the compiler will be explained.

The compiler is envoked from the IDE through one of the Compiler
menus, an accellerator key, or by pressing one of 4 speed buttons
regarding this. In the "Messages" window, you will be able to follow
the compilation. If an error occurs, it will be described in that window,
and the carêt will point on the error in the appropriate window.

If you want stand alone compilation instead, you must use the DOS
version of the compiler.

There are 4 different ways of starting the compiler, Compile, Make,


Build and Make/Run.

In "Compile" (Ctrl+F9) you just compile the source in the front editor
window. No linking takes place.

In "Build" (Ctrl+F12), you (re-)compile and (re-)link all the files in


your project. Your project is the file that you entered using File|Project
main file. It's name is shown in the SYS51W caption after the - .
Please notice this as one very common mistake is to think that the
source in the front editor window is build. Please also notice that this is
different from the convention in the DOS IDE version.

"Make" (F12) is similar to "Build", but the (re-)compile and (re-)link is


"clever", only when changes have taken place, the appropriate
operations will take place. Basis for the "Make" is the project as in
Build.
PAS51 33
________________________________________________________

"Make/Run" first does a Make on your project, and after that calls
a progam to execute your project. Which program to execute (default
integrated simulator) depends on the setting in Run|Setup. If no project
is given, the execution program if external, will start without loading
any target program.

After a successful "Build", "Make" or "Make/Run", the following files


are generated:

1) A .HEX file containing the complete translated program code


in INTEL HEX format

2) A relocatable .OBJ file, which will (if the #pragma debug


compiler directive is on) also contain information on variable
names, their addresses, and information on where PAS51W
source statements starts in the program code.

3) An optional .ASM file containing the program translated to


an assembler source mixed with the PAS51W source lines as
comments.

4) An optional .LST file containing the source file with source


statement numbers and block levels. This is intended for the
usage by third party emulators.

5) An optional .UBR file containing absolute and debug


information in the IAR UBROF format. This is intended for
the usage by third party emulators.

If you do not use the module facilities, it will also generate the
following:

4) An .A51 absolute file compatible with that of INTEL without


extension.

5) A .MAP file.
34 SYSTEM51
________________________________________________________

Whereas files 1) and 4) are fully linked to the runtime library, this is
not the case with 3). EXTRN pseudoops are generated to all used
entries in the library. If you assemble your source code modules written
in assembly language with the ASM51 supplied with this package, the
linker will link the files FP51.OBJ, PL51.OBJ, and IODRIVER.OBJ at
the end of your LINK51 process. If you for some reason use another
assembler, the file IODRIVER.ASM may be included or linked by
using that assembler.

If there are errors in the source of your PAS51W program, the


compiler will report an error with the error type and the line number.
You may now choose how to proceed.

6. The Integrated Simulator

If you just a simple simulation of your high level program, use the

built-in simulator. The buttons are used to operate


that. The buttons are from left to right: run, stop, step over and step
into. To prepare the running man for this use, “Run|Setup|Name of run
program” must be set to “(integrated simulator)”. After pressing one of
the buttons, run, step over or step into, a make will take place, and if
success, the following extra window will show up:

as part of a picture like this:


PAS51 35
________________________________________________________

In the RUN window you may watch the current PC value, the escaped
time (12 Mhz Crystal), the values in hex of your program variables and
selectable either a small window of the data, sfr or xdata window or the
8 registers. If stepping, a green bar in the program source will show the
line, containing the statement just executed. SBUF communication
(also read(ln)/write(ln) )will be simulated using the ‘Message Window’.
36 SYSTEM51
________________________________________________________

7. The (External) Simulator.

7.1 Overview of the Simulator.

The SYSTEM51 simulator is a program that allows 8051 programs to


be tested on a PC. Every 8051 instruction will be interpreted and
executed by running a small part of a program on the PC. As this takes
a lot more time than the 1 to 4 microseconds per instruction in the real
chip, the simulated running is slower than execution on the target
micro, but many bugs might be discovered with this tool.

The simulator is called from the IDE by typing Shift-F9 or Alt-R/S or it


may be clicked on directly from Windows or, if properly setup, by
clicking the running man in the speed bar.

You may open up to 14 different child windows, assisting you in


different ways by debugging your software.

If you have written your programs in one of our high level languages
SYS51C or Pascal, the source text of your project .C or .PAS file will
appear in a window on your screen when entering the program. This
window information may be used in both directions, i. e. breakpoints
and listpoints will be shown in the source text, and you may set
breakpoints, go from- points and listpoints by referencing statement
boundaries shown in the text window.

Whether or not you use the hll window facility, you will be able to
debug the program on an assembler symbolic or absolute level.

When running simulation, the built-in timers will run at (simulated


instruction) programmed speed and may cause interrupts to be
(simulated) run. Input and output must be done by examining and
entering values from the keyboard to the RAM-Port addresses. Break on
(simulated) time is provided.
PAS51 37
________________________________________________________

One major exception exists to this. Serial buffer input/output will be


treated in a special way. Output will be written to a special RUN
window. Keyboard typing except ESCAPE will be output to SBUF.
This facility allows you to use the SYS51C built-in procedures scanf
and printf and the Pascal Write(ln) and read(ln). This means that serial
buffer input/output will work exactly as if a terminal had been connec-
ted to the serial data pins: serial data may be polled or may be read by
using the PROCEDURE INTERRUPT SERIAL in the PAS51W langu-
age. I/O to/from the RUN window may be redirected by the use of the
commands WRITE or READ which you access through the File menu
or by writing commands in the COMMAND Window.

7.2 The Simulator Screen.

On start up time of the simulator, in order to debug SYS51C or Pascal


programs, the screen will consist of 4 different parts.
38 SYSTEM51
________________________________________________________

1) The upper line on the screen is the menubar line. You may
pull down the menus listed by clicking the mouse or pressing
keys Alt-the_Highlighted_Letter.
When a menu is pulled down, you may click the item, move
the colored bar with cursor up/down and press Enter, or press
the highlighted letter.

2) A speed button bar, allowing you to fast enter some often met
commands.

3) A HLL-code window showing your source code. This may be


used for setting breakpoints, following execution, and so on.

4) At the buttom, a STATUS line with some messages.

7.3 Running the Simulator by hotkeys and pull down


menus.

It is possible to run the simulator entirely by pull down menus,


accellerator keys and speedbuttons.

The menus are:

File Load or save different files; exit


View View one (or more) of the 14 windows
Watch Add, edit or delete watch(es)
Display/Set Display and / or modify variables or registers.
Run Run or step program; set run/step modes
Search Search for text in PAS51W source window
Macros Define, execute, or show macros
Window Reposition or resize windows
Help Get online help
PAS51 39
________________________________________________________

7.3.1 The Simulator File Menu.

Load... Load new code- and symbol information


Modules... Activate Module
ListFile... Open / close command disk output
WriteFile... Open / Close SBUF disk output
ReadFile... Open / Close SBUF disk input
---------------------
Port Stream In... Open disk stream for port input
Port Stream Out... Open disk stream for port output
----------------------
Exit Exit Simulator (to where you came from)

Load new code-, hll- and symbol information

You may Load other .C, .PAS, .HEX, . or .A51 files than the default
by start-up time. . Files without an extension (no extension) or .A51
files contain code, symbol and statement information, whereas .HEX
files
contain only code information. .A51 files must correcpond to .PAS or
.C files for HLL's to be loaded.

Change Modules

In this dialog box, you choose which module you want to look at. You
may optionally have the choice of all modules or modules,
corresponding to some C or Pascal source text When running the
program, the system itself will select the HLL module, to which the
program counter actually points.

The ListFile, Writefile and ReadFile submenus

Some of your communication may go to / come from disk files. With


ListFile... active, output to the command window will also go to disk.
40 SYSTEM51
________________________________________________________

With WriteFile... active, output to the RUN window will also go to disk.
With ReadFile... active, input to the SBUF, normally taken from the
keyboard when the RUN window is active, will instead come from disk.

The 2 disk output facilities will be closed either when you once again
click the menu item, or when you exit the simulator.

Port Stream In... and Port Stream Out...

Port Streams

Port streams are text files that help you to control or watch port value
history. Output port streams let a (simulated) running program generate
such a file for you to either use for input later or to analyse by the
graphic port window facility or by any text editor.

Port streams may also be used for controlling port inputs during
(simulated) program run.. For this purpose use port stream files,
generated by either an output port stream or a text editor.

Port streams are text files with either extension .PTD or .TXT and have
the format:

<Port_name>
<time1> <value1>
<time2> <value2>
...

The 1. line gives the port name, from where the file originates, and
which name is passed to the graphics port window. When using the
port stream for port input streaming, this line isn’t used.

The next lines contain two decimal, positive numbers, separated by one
or more spaces or tabs. The 1. number, a 32 bit unsigned integer, gives
the time in clock cycles (1 microsec. °12mhz crystal freq.) that the 2.
PAS51 41
________________________________________________________

number will be the value of the port. This 2. number is an 8 bit


unsigned decimal number.

Please notice the following exceptions from a full implementation:

1 The bus timing on port P0, P2 and P3.6 and P3.7, in case of
external memory, isn’t implemented and shown.

2. The on-chip or’ing of the pin input signals and the chip-
internal output flip-flop isn’t implemented.

3. As the serial channel is simulated in a different way, no


communication signalling takes place on P3.0 and P3.1.

Input Port Streams

Port value timing may be controlled by Port streams. A port stream is a


text file stored on disk with the extension .PTD or .TXT. You connect a
port stream to aprocessor port by invoking the File/Port input Stream
menu point. If you use this menupoint on an already opened port, the
open file will be closed instead.

You may generate such a file either by using any text editor, or by
letting an output port stream generate it for

Output Port Streams

Information about port changes during (simulated) run may be


outputted to port streams. To invoke this facility, select the menu point
File / Port Stream Out.

The stream will be outputted as a text file with an extension of .PTD or


.TXT. Up to 6 different streams may be open at a time. Using the menu
point on a port with an open stream will close that stream.
42 SYSTEM51
________________________________________________________

Please notice that there is no upper limit of the size of the file, only the
limited size of your disk. If your program changes your port very
rapidly, be prepared to stop the simulated run at an appropriate
moment.

Exit simulator

You may Exit the simulator by typing Alt-F4 or press the exit key. You
return to where you entered the simulator, probably the IDE.
PAS51 43
________________________________________________________

7.3.2 The View Menu.

The simulator contains the possibility to open a lot of views in


different windows, see:

Hll Window High Level Language View


Watch Window Watch View
---------------------
DataWindow Internal RAM data memory in hex
DisasmWindow Disassembled View
XDataWindow External RAM data memory in hex
CodeWindow Program (code) memory in hex
-------------------
Stack Window Stack info with function names and returns
Cpu Window Different registers and status info.
Register Window Current register bank
Sfr Window Internal SFR memory in hex
----------------------
Run Window I/O for the SBUF serial channel
Command Window For controlling by commands
Statistics Window Shows run profile graphically
Port Timing Diagrams Shows port streams graphically

High Level Language View Window

The High Level Language (HLL) window will show you where you are
in your C or Pascal program. You may set and delete breakpoints here,
follow the execution of your programs, see corresponding assembler
code, and enter watch symbols in the watch window by pointing on the
symbol name here.
44 SYSTEM51
________________________________________________________

Different Memory Type View Windows

The DATA (Alt-V/T), XDATA (Alt-V/X), and SFR /Alt-V/F) and


CODE (Alt-V/O) memories each have their own View window.

You may open them by pulling down the View menu and click the
item.

To change a value in such a memory, just click or place the cursor over
the value at the wanted address, and start typing the (hex) value. If you
want to see / change an address that is not in the window, you may
scroll to it or you may just place the cursor over the address and type a
new one.

If you want to enter the value in a symbolic way, use the


Display / Set Menu, Substitute submenu.

The CPU View Window

The CPU-Window will show the current value of selected registers like
the PC, Acc, PSW, B, SP, DPTR and ports. It will also show you the
elapsed time since program run started.

To see / change the values of the registers R0-R7, see the Register
Window

To change values, you may click on the appropriate position or place


the cursor at the item, then start typing the new value.

To show the correct time, the clock frequency must be that of your real
hardware.
PAS51 45
________________________________________________________

Dissassembled code View Window

In this window, you see a disassembled portion of your program.

There are three sorts of "cursor marks" in it. The cursor you move with
the mouse or the cursor keys are marked gray.

If the PC value is within the window, you see a green bar on that
position.

If a breakpoint is set, a red bar appears. Breakpoints may be set/reset by


pressing F2 or doubleclicking the mouse.

In an animated run, you will see the green bar move around in this
window.

Stack View Window

The stack window shows the functions / procedures called at the


moment. If the system can find its symbolic name, it will write that,
otherwise it will write the address. If you doubble-click on a function,
you will be brought to the place, from where it was called.

Register View Window

The REG-Window will show the current value of registers both as 8 bit
items and as 16 bit double registers.

To see / change the values of selected special function registers like


ACC, B SP or ports, see the CPU Window
46 SYSTEM51
________________________________________________________

To change values, you may click on the appropriate position or place


the cursor at the item, then start typing the new value.

Run View Window

If SERIAL ON (default), this window will show you the SBUF SERIAL
output from running programs. If your program needs SBUF input,
what you type on the keyboard will be send to your program if the
RUN-window has the focus.

It might be brought to the foreground by clicking on the menu (Alt-


V/U)
or automatically when a running program starts to output data to
SBUF.

If you don't want this SBUF feature, go to the Command View Window
and
type SERIAL OFF.

The RUN window may be opened by either clicking on the menu (Alt-
V/U) or automatically when a running program starts to output data to
SBUF.

If you don't want this SBUF feature, go to the Command View Window
and type SERIAL OFF.

The Statistics (Profile) Window

This window shows you statistical information about your program


execution.
PAS51 47
________________________________________________________

A graphical bar picture shows the relative amount of time that a


program spends when executing at different areas of your memory. In
this way you will be able to isolate bottlenecks in your programs.

To enable recording of statistical information (which will slow down


the execution speed) you must enable the recording statistics check box
in the recording dialog box.

With the two scrollbars you may set the display area and scale.

Port Timing Diagrams

Port streams may be graphically displayed in this window. You may


open it using the menu point View / Port Timing Diagrams.

The two scrollbars at the buttom of the window will allow you to
change the scale of the time axis and to mode the zero-point, all
allowing you to get a broad view of the timing, or to study details
everywhere. The are not so many fix-points, but placin the mouse at a
certain point will give you the exact coordinates.

The input to this window must be a port stream, which may come from
an earlier generated port sreeam file either from an earlier run with the
port output stream facility enabled or from a file, written by using a
standard text editor.

The Command View Window

The Command view window is used to enter commands from the


keyboard.

The window consists of two parts a lower and an upper part; you will
enter your commands in the lower part. As this is a combobox, you will
easily be able to repeat commands: just draw down the list and click.
48 SYSTEM51
________________________________________________________

If you list the content of macros, this will be done in this window.

In the next chapter 6.4, we will review which commands to enter in this
window to operate the simulator.

7.3.3 The Watch menu

Add... Ctrl+F7 Add a new watch; Pointed text will be suggested


Edit... Edit existing watch; enter by number
Delete... Delete single watch; done by number
Delete All Delete all watches.

The Simulator Add Watch Facility

In the watch window, you may see the value of variables during the run.

If you have a Hll window, the cursor may be placed above the symbol
to enter. Type ^F7 then enter. Otherwise type ^F7, write the
symbolname then press
enter. If the symbol is a name in a HLL program, it will be shown in
the type, declared there; otherwise it will be shown as a byte. If you
otherwise want the item displayed as a special type other than byte,
add a space and then the type letter. Type letters are

B for byte in hexadecimal


D for (16 bit signed) decimal
W for (16 bit unsigned) hexadecimal
C for ASCII code of byte
A for array of byte (in hex)
S for string (Pascal type or C type depending on language)

With the Simulator Edit Watch Menu, you may change already entered
watch expressions. Enter Alt-A /E then the number of the item (given
left in the watch window). Correct the spelling and press ENTER.
PAS51 49
________________________________________________________

To change the value of a variable, you should use Display/Set,


Substitute instead.

You may delete one watch at a time or all.

To delete all, enter Alt-A/L or click the item.

To delete only one, enter Alt-A/D or click the item, then enter its
number (given left in the watch window).

7.3.4 The Display/Set Menu

Substitute... Shift+F4 Show/modify variable or


expression
Assemble... Line oriented assembler
Display Program Addresses... Display/modify different addresses
Fill... Fill part of a memory with a
constant

Substitute...

You may delete one watch at a time or all.

To delete all, enter Alt-A/L or click the item.

To delete only one, enter Alt-A/D or click the item, then enter its
number (given left in the watch window).

Assemble...

First you will see a dialog box, asking for an address expression. This
may be absolute in hex, symbolic preceeded by . or statement number
preceeded by #.
50 SYSTEM51
________________________________________________________

After that you should enter symbolic assembler lines in the next dialog
boxes; an empty line will end the entry.

Display Program Addresses...

You will see the content of the showing address point in the program. If
you want to change it, just enter the new value and type enter.

The new value may be absolute (number in hex), symbolic (preceeded


by a ".") or statement number (preceeded by #).

To change the Program Counter (PC), from where a run will continue,
use the CPU window

Fill...

Three dialog boxes will follow, the first should give the start address
in one of the memories, the next the final address, and the last a content
byte.

The start address should give not only the address, but also the memory
type. This may be done by preceeding a hex number by one of the
letters
P (code mem), X (xdata mem), R (data and idata mem) or S (sfr
memory), or
it may be done symbolically (label, variable or function/procedure name
preceeded by ".") or by statement number (preceeded by "#"), the latter
giving the code memory.

7.3.5 The RUN Menu

Run F9 Start running the program


Here F4 Run to current cursor point
Animate Ctrl+F9 Run while showing where
PAS51 51
________________________________________________________

Step Into F7 Step one instruction or statement


Step Over F8 Step, but run function
Trace Back... Show recorded trace buffer
Exec Macro... Start executing macro
---------------------------------
Toggle Breakpoint F2
Advanced Brp... Breakpoints, other than code addresses
---------------------------------
Step Mode Step on statement or instruction
Recording... Start filling the trace buffer
Reset Target Ctrl+F2
---------------------------------
Options Different runtime options may be set

Run (F9)

You start a run by pressing the RUN button or you may use F9. In
the buttom status line, simulated time will be shown; otherwise you
won't see the program run, except if your program uses the serial port.
In that case, the RUN window will be your connection. The green field
in the status line will show "RUNNING" or "RECORDING" depending
on whether the trace buffer facility is enabled or disabled. If the
program counter meets a breakpoint, it will stop. Otherwise to stop
running, press ESC or the break button.

Here (F4)
By pressing F4 while in the HLL window, you will set a temporary
breakpoint at the pointed statement and then start a running as above.

Animate Ctrl+F9

If you use animation ^F9 you will see the following: If you have a hll
view open, the cursor will move around to the executed positions; if you
have a list view open, the just executed instruction will be highlighted
green; if you have a watch view open, the symbols values will be
updated.
52 SYSTEM51
________________________________________________________

The animated run may be stopped when passing a breakpoint, by


pressing ESC or pressing the break button:

Step Into F7

This function steps one instruction or one statement, depending of


which window is open or of the "Step Mode". If the HLL Window is
active, statement stepping is used if no special mode is set; if the
DisAsm window is set, instruction stepping is used.

Step Over F8

This function is the as F7, except that it do not step into functions, but
runs the whole function in one step.

NB. NB. Do not use F8 as the very first step. You must use F7 instead.

Trace Back...

This dialog box shows you some peviously recorded execution data.

Using the scrollbar you may mode back and forth in the execution
history. Please notice that the hll window, the watch window and the
disassembly window will follow the history. Also please notice that no
other windows will be updated.

Exec Macro...
PAS51 53
________________________________________________________

In this dialog box, you might start execution of a macro; for how to
make a macro, see advanced commands or Edit Macros

Toggle Breakpoint F2

The simulator contains both simple breakpoints (on Program Counter


values) or advanced breakpoints using virtually any expression as a stop
condition.

Simple breakpoints may be toggled by pressing F2. Breakpoints will be


shown as red bars in the hll and list views. When the list view is the
active window, the cursor position there will be the toggled position,
otherwise the hll view cursor position.

Advanced breakpoints

This dialog box, envoked by the menu item Alt-R/A services two
purposes: to set/reset complex expression breakpoints, and to see which
simple breakpoints are set and possibly go to an address, were a simple
breakpoint is set.

In both cases, a combobox allows you to edit old breakpoints and to add
new

Recording...

This facility allows for recording execution of up to 512 statements or


instructions.

The dialog box, included in this facility, contains 4 check boxes, 4


address entry points and a OK button and an ESCAPE button.
54 SYSTEM51
________________________________________________________

The check boxes are

1) Recording On ; Enable / disable the recording facility


2) Recording PC only ; Do not record more than the PC to save
time
3) Stop if Buffer Full ; Stop when all buffer is full / only stop on
BRP or manual STOP
4) Recording Statistics ; Collect data for the statistics / profile
window

To see what was recorded, use the traceback dialog box.

Reset Ctrl+F2

^F2 will reset the (simulated) target, i.e. PC will be set to 0000, SP to 7,
interrupt to off, port P0 to P3 to 0FFH and all other SFRs are set to 0.
As in the real chip, the memories and the other registers are not
affected.

Options.

A multitabbed dialog box will show up. The leftmost tab is concerning
how the serial port (serial port 0 in those derivatives with 2 serial ports)
will be simulated.
Default is “Baud rate simulated”. The appropriate timer (normally
timer1) will run the correct number of ticks (simulated) to send /
receive a character. Please notice that there is no check that this leads
to a correct baud rate on the real target. As especially using animation,
this way of simulation may seem very slow, there are two other
selections of simulation modes: “Immediate” where the character is
send / received immediatly without any delay, and “off” where you have
to manually set TI / RI when a character has been send / received.
Please notice that “Immediate” may cause problems when working with
serial interrupts.
PAS51 55
________________________________________________________

In the left but one tab area, you may set a animation delay count. As
this is implemented by a software loop, the actual speed will depend on
the speed of your PC.

In the right but one tab area, you setup how much xdata you have in
your target and if some parts of this are overlapped with the
corresponding code area. Please notice that you also have to enable
xdata areas containing memory mapped I/O to get a proper result.

The rightmost tab area is concerning simulation of big systems


containing more than 64K xdata and / or 64K code. Only bank
switching is implemented. The Dallas Semiconductor 80C390 linear
model isn’t implemented.

7.3.6 The Macros Menu

Edit... Enter new or change macro text


Execute... Execute macro by taking command input from
macro
Load... Load macro from disk
Save... Save macro to disk

Macros entered in the Edit box have the same syntax and semantics as
described in the "Advanced Commands" section of this manual, except
that the "DEF :" command word must be omitted, i.e. a macro consists
of a sequence of commands, ended by "EM". This ending EM (end
macro) is already placed into the text.

7.3.7 The Search Menu

Find... Ctrl+F Find some text in the HLL window


Find Next... F3 Find next position of the same text
Go to line #... Go to a line number in the HLL window
56 SYSTEM51
________________________________________________________

7.3.8 The Window Menu

Tile Tile the open windows (see all)


Cascade Cascade the open windows (see caption of all)

7.3.9 The Help Menu


Index F1 Open main help index
Topic Search Ctrl+F1 Open help on current topic or search box
How to Use Help
-------------------------------
About... Version, license # and license holder

7.3.10 The accellerator shortcut keys

F1 get on screen help, sensitive of where you are.


^F1 get on screen help, sensitive to topic
F2 Toggle breakpoint at the cursor in list view win-
dow if selected, otherwise at the cursor in the HLL
source window.
^F2 Reset processor.
F3 Search Next.
^F4 Close selected window.
Alt-F4 Exit program
F4 Execute program from current PC to current
cursor (HLL source or disassembly list view).
^F6 Next window.
F7 Step, also into function
^F7 Enter Watch dialog box
F8 Step, but skip function call
F9 Run from current program counter value.
^F9 Same as in F9, but animate (show program
execution in HLL source view, list view and
watch).
F10 Goto menu bar.
PAS51 57
________________________________________________________

7.4 Running the simulator by commands.

If you want to run the simulator in a more conventional way using


command sequences, this is possible by opening the command view
window, Alt-V/O

7.4.1 Command Language.

The commands mentioned in this chapter may either be entered from


your keyboard into the lower part of the command view window, or be a
part of a macro. The command window lower part offers you normal
Windows editing facilities.

7.4.2 Format of expressions.

In expressions, operands may be numbers in hex, symbolic names


preceeded by ".", C or Pascal statement numbers (in decimal) preceeded
by "#" or the current value of the program counter, PC. Operators may
be C-like +, -, *, /, &, &&, !, ||, (, ), [, ], the latter denoting the contents
of a memory position rather than an expression value or Pascal like +,-
,*,/, and, or, not, (, ), [ or ].

Unlike in the C source, simulator expressions and names do not


distinguish between upper-case and lower-case letters.
58 SYSTEM51
________________________________________________________

Expressions may or may not have a memory type assigned. In case of a


HLL statement number, the assigned memory type is CODE. In case of
a symbolic name, the assigned memory type is that of the symbol in
HLL or assembler, which may be DATA, XDATA, CODE, BIT, SFR
or ABS (no memory assigned).

Some commands (S and D) must have a memory type assigned. You


may explicitely express the type of the wanted memory by prefixing an
expression with one of the letters R, I, S, X, P or B, where

R or I denote the internal RAM memory,


X denotes the XDATA external data memory,
S denotes the special function register file,
P denotes the CODE program memory, and
B denotes the boolean memory or SFR bit register file.

Examples:

Suppose you have specified the following PAS51W declarations:

var
mychar: byte data;
myarray: array[0..5] of byte data;

procedure myproc; (* statement # 25 *)

then some examples of legal expressions may be

#25
(#25)
.myproc
.myproc+3
.myproc - PC
.myarray + 2 * 2
.myarray + [ mychar ]
.myarray + [ mychar + 1 ] & 7F
PAS51 59
________________________________________________________

7.5 The Commands.

7.5.1 Examining or Modifying Memory or Registers.

The L, A, D, S, X, F commands are used for examining and/or


modifying the contents of memory positions or register contents.

The L and A commands operate in program memory in symbolic as-


sembler. The L lists the current content of some part of code memory,
whereas A is used for entering new or modified instructions.

The syntax of the L command is

L[<list_start>][,<list_stop>]

Disassembly will take place from <list_start> or a default address,


calculated from the past history of the simulator, to <list_stop> or a
screenfull of disassembled instructions. <list_start> and <list_stop> are
expressions.

The syntax of the A command is

A<assemble_start>

where <assemble_start> is an expression which value designates where


to start line assembly.
The entering of assembly lines will succeed until an empty statement is
entered. When an attempt to enter an illegal or misspelled instruction is
done, a question mark (?) will appear, and you have to reenter the
instruction. Because the character "#" has different meanings (ie. either
an immediate instruction indicator or a line number indicator), the
convention is that line numbers in case of the A command must be in
parenthesis ().
The symbolic instruction names used in L and A commands are the
same as in the INTEL standard.
60 SYSTEM51
________________________________________________________

Examples:

-A2000
2000 mov dptr,#1234*2
2002 mov t2,0s
?
2002 mov r2,5+5
2004
-L2000,2003
2000 MOV DPTR,#2468
2002 MOV R2,0A
-L#1,#3
002B MOV 43,#0
002D MOV 44,#0
-

The D command is used to display parts of one of the memories in hex.

The syntax of the D command is:

D<startpoint>[,<stoppoint>]

<Startpoint> and <stoppoint> are parameters indicating the boundaries


of memory to display. <Startpoint> and <stoppoint> are expressions.
These expressions must have a memory type assigned or explicitly
mentioned.
PAS51 61
________________________________________________________

The S command is used for examining and modifying in hex, single


locations in internal data ram, external data ram, special function
registers, or program memory.

The syntax of the S command is:

S<first_address>

where <first_address> is an expression returning a memory type.

After typing the S command and Return, the memory type, the address
and the value will be shown.
You may now optionally enter a new value and then type return. The
next location will then be shown, you may alter it until a .<Return> is
typed.

With the X command you may examine and/or modify registers. An X


alone will show them all. Typing one more letter will cause the
simulator to display the content of that register and wait for a new
value. Type the new value as an expression followed by a <Return> or
leave the content unchanged by entering a <Return>. Possible registers
are

XA The accumulator
XRn Register Rn, where n is a number between 0 and 7
XP The Program Counter PC
XT The elapsed simulated time in milliseconds

Registers not mentioned above may only be modified by the S


command.

The F<memtyp><start><end><value> command will fill a portion of


one of the memories (R,I,X,S,B,P) with the value <value>.

The N command will display a list of all symbolic names currently


loaded and their corresponding addresses.
62 SYSTEM51
________________________________________________________

7.5.2 Run and Trace Commands.

The G command forces the program to execute.

The syntax of the G command is as follows:

G[P][<start_address>[,[T]<breakpoint>][,[T]<breakpoint>]

<Start_address> is an expression denoting the starting point of the


execution. If missing, the current value of the PC is used.

<Breakpoint> is an expression denoting an address or time where to


stop execution if met. If <breakpoint> is preceeded by the letter T, then
a time is used, otherwise an address.

In case of a T breakpoint, T milliseconds from the start of the


simulation or from the last setting of the simulated time is used (see the
XT command).

Execution of a program may be stopped by pressing ESC.

The GP command acts exactly like G except in one way. While


executing, the C statement corresponding to the actual program counter
value will be shown in the high level language window. If opened, the
values of the symbols in the window will be updated.

The T command forces a step in execution from the current PC value to


the next. After the step, the main registers will be shown.

Multiple traces may be performed by adding a number to T.

The TP command forces a one HLL statement step.

The O and OP commands (step Over commands) act like the


corresponding T and TP commands except that whole subroutines
(procedures, functions) are treated as one instruction or statement.
PAS51 63
________________________________________________________

7.5.3 SETUP Commands.

SETUP DELAY (abbreviated SE DE) will insert a delay every time the
GP command displays a statement boundary in the upper window, so
you may have a chance to follow what is happening, even on a fast PC.
The choice of the delay value depends on you and your PC, but try for
instance 2000.

SETUP SYMBOLS (only SE SY is necessary) will setup a window


showing up to 10 variables with names and values, even during GP
run. Memory type expressions must be entered. Unless an extra
parameter is used, values will be presented as byte in HEX. Possible
type parameters to expressions may be W for 16 bit unsigned integers
in hex, D for integer values in decimal, C for character values, S for
strings (only the first 4 characters presented), R for reals, A for arrays
of bytes (4 bytes presented in hex).

7.5.4 DOMAIN command.

DOMAIN (abbreviation DOM) chooses the module used for searching


local symbol names and showing C text in the upper window. Write:
DOM <filename> , where <filename> is the file (.C) and module
(.A51) name without extension. Note that the module and file names, as
well as the time of creation must match.
64 SYSTEM51
________________________________________________________

7.5.5 LOAD command.

At start up time of the simulator when called from the system menu, the
file with the name <filename>.A51 will be loaded. The code, symbol
table and upper window HLL source will be automatically loaded. If
you later on during the execution want to reload or load additional files,
use the LOAD command.

Syntax:

LOAD <filename>

If the <filename> has the extension .HEX, the INTEL HEX file format
is assumed, otherwise an INTEL compatible absolute file. (In this
system with the extension .A51).

7.5.6 LIST command.

The LIST command will redirect a copy of the command view window
output to any DOS file or device.

Syntax:

LIST <filename>|STOP

In case of a <filename>, this file will be opened and the output will be
sent to that file. In case of STOP, the output redirection will be stopped
and the file closed.
PAS51 65
________________________________________________________

7.5.7 WRITE command.

The WRITE command will redirect a copy of the runtime SBUF write
or writeln output to any DOS file or device.

Syntax:

WRITE <filename>|STOP

In case of a <filename>, this file will be opened and comming output


will be sent to that file. In case of STOP, the output redirection will be
stopped and the file closed.

7.5.8 READ command.

The READ command will redirect input from any DOS file or device to
the runtime SBUF C device.

Syntax:

READ <filename>|STOP

In case of a <filename>, this file will be opened and input taken from
that file. In case of STOP, the input redirection will be stopped and the
file closed.
66 SYSTEM51
________________________________________________________

7.5.9 CALC command.

Calculates an expression. Syntax:

CALC <expression>

The value of the expression will be shown in hex and decimal. Also the
memory type will be shown.

7.5.10 DEF command.

Syntax 1:

DEF .<variable> = <expression> [<memory_type>]

This form defines a new variable (label) with the value of the
expression and of the memory type given in <memory_type>. Valid
memory types are CODE, DATA, XDATA, SFR, BIT, or ABS.

Syntax 2:

DEF :<macro>
<macro body>
EM

<Macro> is the symbolic name of the macro. <Macro body> consists of


one or more commands. Formal parameters may be given in the
<macro body>. Such parameters consist of a "%" followed by one
decimal digit like %7.
PAS51 67
________________________________________________________

7.5.11 Structured commands inside macros.

Inside macros, structured command execution is possible. The construct


IF expression ... [ELSE] ... ENDIF makes it possible to do conditional
execution, whereas the REP ... [WHILE expression] ... [UNTIL
expression] ... ENDR construct allows repeated execution of
commands. The constructs may be nested.

IF expression
Inside a macro, it offers conditional execution of
commands. If "expression" is true, (i.e. bit0 =
1) the following commands are executed until an
ELSE or an ENDIF is met. In case of an ELSE
met, commands after ELSE and until ENDIF are
executed if the "IF" expression was false,
otherwise not.

ELSE See IF

ENDIF See IF.

REP The commands inside a macro between REP and


ENDR will be repeatedly executed until a WHILE
expression becomes false or an UNTIL expression
becomes true.

ENDR See REP.

WHILE expression
See REP.

UNTIL expression
See REP.

Example of a macro:
68 SYSTEM51
________________________________________________________

DEF :CRUN
ECHO OFF
REP
TP
IF .XX>22
ECHO ON
CALC .XX
ECHO OFF
ENDIF
UNTIL PC>#24
ENDR
ECHO ON
EM

This macro will step HLL statements until the program counter gets a
value greater than code address for statement 24. During stepping, the
variable XX will be shown if its value is greater than 22H

7.5.12 Executing macros.

Syntax:

:<macroname> [<parameter>]{,<parameter>}

This will execute a macro by the name <macroname>. The optional


parameters will replace %0, %1, etc. in the macro definition text.
PAS51 69
________________________________________________________

7.5.13 INCLUDE command.

Syntax:

INCL <filename>

Redirects command input from the file <filename>. May be used for
start up or reading in previously defined macro definitions.

If you want to activate an include file at start up time, you may enter a
start up file name in the opT)ions submenu in the system menu, or you
may use the /I switch when the system is started stand-alone mode.

7.5.14 PUT command.

Syntax:

PUT <filename>

Puts all defined macros into the file named <filename>. May be read
back again later by the INCL command.
70 SYSTEM51
________________________________________________________

7.5.15 MACRO command.

Syntax

MAC
or
MAC :<macroname>

The first command displays all defined macros.

The latter form displays on the screen the macro by the name
<macroname>.

7.5.16 PAUSE command.

PAUSE waits for a keypress.

7.5.17 ECHO command.

Syntax:

ECHO ON|OFF

inside a macro, lower screen command output will be turned on /off.


The LIST file or ^P print on facility will not be changed.
PAS51 71
________________________________________________________

7.5.18 REM command.

REM remark

Inside a macro, this is intended for comments. Do not use "%" inside
comments as they will be expanded.

7.6 Organization and limitations.

In the simulator, the program space and the external data memory
space is separated. The maximum size of each of these memories is 64
KBytes ( 0 -> 0FFFFH ). In your real hardware, you may have
overlayed some parts of those memories; this will not be simulated.

In the real 8051 processor, the parity flag bit is set after every
instruction execution. In the simulator this is omitted in order to get
reasonable simulation execution speed. All other instructions should be
executed exactly as on the chip. The (simulated) execution time
appearing in the register window is calculated using a clock frequency
of 12 Mhz by default. You may change this in the CPU window. The
time calculation regards the original 8051 with 12 or 24 oscillator clock
cycles per instruction. The compressed, pipelined execution of the Intel
80C251 (in compatible mode) and the Dallas Semiconductor 80C320 is
not simulated.
72 SYSTEM51
________________________________________________________

8. Emulators.

Different of ways exist to debug and test your programs in a real chip.
The best way is to download the program to an In Circuit Emulator
(ICE) connected to the chip and test and debug your program through
that ICE. A simpler, but a little less efficient and limited way is to
include a special monitor program in your program space, and then
place the code under test in RAM memory. Special software providing
both sorts of debugging environment with the same HLL window
facility as the simulator exists, but must be ordered separately.

Emulators and printed circuit boards with monitors currently fully


supported by the SYSTEM51 are:

KSC Software Systems DEBUG51


KSC Software Systems DEBUG51W
Mandeno Granville Electronics DBGX552

To use other In Circuit Emulators you may use the "Generate IAR
UBROF" option or the SYMCONV program described in chapter 10 of
this manual to get acquainted with some high level debugging features
in your system.

Emulators, know to respond correctly to the "Generate IAR UBROF"


option, are:

MetaLink
V'Nice-51
PAS51 73
________________________________________________________

9. The Assembler ASM51.

The assembler ASM51 will translate 8051 assembler source code


(.ASM) to a relocatable and linkable object file (.OBJ) suitable for
linking with the program LINK51W, supported in the system51
package. A list file ( default .LST) will contain a listing of the file. The
mnemonics for the instructions are completely compatible with the
INTEL format.

To call the ASM51, just call it from the IDE menu, Compiler|Assemble
(Ctrl+A)

In the .ASM source text, capital letters and lower-case letters are
completely intermixable.

Labels must be followed by a colon except before EQU, DATA,


IDATA, XDATA, BIT or GSET.

Numbers may be decimal, hexadecimal (a H must follow the number)


or binary ( a B must follow the number).

Operands for both instructions and pseudoops may use labels, numbers
and the operator $ denoting the location counter, either alone or
combined by the operators +, -, *, /, &, and !. A dot "." will cause the
calculation of a bit address of either a SFR or a variable. & and ! denote
bitwise AND and OR.

The following pseudoops are available:

ORG XXX moves the location counter to


location XXX (relative to
module or library start)

END ends the module.

YYY EQU XXX


declares the label YYY equal to XXX
74 SYSTEM51
________________________________________________________

YYY GSET XXX


as EQU, but this declaration holds
throughout the file when more libraries
are used.

YYY DATA XXX


YYY BIT XXX
YYY XDATA XXX
YYY IDATA XXX
All these pseudoops will act like EQU.
They are included for reasons of compa-
tibility with the intel assembler and to
help you structure your data. Use them
whenever possible as a coming release
wil use the information for data
relocation.

DB XX1,XX2,...
generates bytes of code with the value
XXn

DW XXX1,XXX2, ...
generates 16 bit words of code with the
low and high value of XXXn

PUBLIC XXX declares a label, elsewhere


defined in the module or
library, public, i. e. known to
other modules at link time.

EXTRN CODE (XXX)


declares a label, defined in some other
module, known at link time. Only code
segment references may be PUBLIC or
EXTERN(AL). If XXX is defined as
PUBLIC in a LIBRARY, that library
file will be linked.
PAS51 75
________________________________________________________

LIBRARY starts a library module. more


libraries may be assembled
together.

LIBEND ends a library module.

CSEG The absolute code segment (default)


DSEG The absolute (low ram and SFR) data
segment
BSEG The absolute bit segment
XSEG The absolute external ram data segment
ISEG The absolute (high ram) data segment

XXX SEGMENT CODE


YYY SEGMENT DATA
ZZZ SEGMENT DATA BITADDRESSABLE
XXX SEGMENT BIT
YYY SEGMENT XDATA
ZZZ SEGMENT IDATA
Define names of relocatable segments
within the segment types CODE, DATA
(low internal RAM space), DATA
BITADDRESSABLE (low internal
RAM space, where the bits are indivi-
dually addressable), BIT (the directly bit
addressable RAM space), XDATA
(external RAM data space) and IDATA
(high internal RAM space).

RSEG XXX Change to segment XXX.

DS YYY Define a memory space of YYY bytes.


DBIT YYY Define a memory space of YYY bits.

EXTRN DATA (XXX)


EXTRN XDATA (XXX)
EXTERN BIT (XXX)
EXTERN IDATA (XXX)
76 SYSTEM51
________________________________________________________

Define external(s), here XXX, within


the mentioned memory segment types.

USING <bank> Declares to the assembler that the bank


<bank> (0 to 3) is used in the following.

<mn> MACRO
[<formal param>{,<formal param>}]
<macro body lines>
ENDM
The name <mn>defines the name of a
macro with optional parameters <formal
param> and the content <macro body
lines>. Do not use $ directives inside
macro definitions. Macro definitions
must not be nested.

<mn> [<actual param>{,<actual param>}]


The macro by the name <mn> will be
expanded. The actual parameters
<actual param> are text strings, not
containing "," or ";", and will replace
the formal parameters with the same
numbers. Macro expansions may be
nested to a level of 10.

IF <expression>
If the <expression> has the value
0FFFFH (true) then the lines until the
corresponding ELSE or ENDIF will be
assembled, otherwise they will not be
assembled. In case of an ELSE is met,
the lines after ELSE and until the
corresponding ENDIF will be
assembled. If-constructs may be nested
to a level of 10.

ELSE See IF.


PAS51 77
________________________________________________________

ENDIF See IF.

$INCLUDE <includefile>
Include the file <includefile>

$DEBUG Force generation of symbol information into the


.OBJ file.

$LINE n <source_line>
HLL line # and corresponding source
code
(line # to be included in the .OBJ file)

$NOLIST Turn off listing.


(Generation of .LST)

$LIST Turns on listing. (default)

$EJECT Force a page eject in the .LST file.


78 SYSTEM51
________________________________________________________

9.1 Examples of assembler programs.

Three examples of assembler programs follows. The first one is a very


simple one. It doesn't use any relocatable segments, any conditional
assembly or macros. It resets a variable, enables an interrupt, counts the
variable on interrupt and shows the value on port 1.

; ASSEMBLER EXAMPLE 1

; In case of no NAME directive, ;


MAIN will be assumed

JMP START
; The absolute code segment CSEG is
; default and starts at 0

ORG 13H

; Interrupt IE1 starts at address 13H

INC VARIA
RETI

START:
; Main program

SETB EA

SETB EX1

MOV VARIA,#0
; Initialization of variable

LOOP:
PAS51 79
________________________________________________________

MOV P1,VARIA
SJMP LOOP

VARIA DATA 20H


; Absolute placed variable in DATA
; area.

END
; End of assembler source

The next example is very much like the former, but the interrupt
routine is placed in another module and the main program is
relocatably placed in a code module. The data is also relocatably placed
and PUBLIC. An assembler directive IF-construct choses between
internal DATA memory and external XDATA memory.

; ASSEMBLER EXAMPLE 2

NAME EXAMPLE2

PUBLIC START,VARIA
; START and VARIA may be called
; from other modules

EXTRN CODE ( EX1INTERRUPT )

INEXT EQU 0
; XDATA switch set false

EX2CODE SEGMENT CODE

IF INEXT
; If true, select XDATA
80 SYSTEM51
________________________________________________________

EX2XDATA SEGMENT XDATA

RSEG EX2XDATA

VARIA: DS 1
; Reserve 1 byte in XDATA
; relocatable area

ELSE
; Otherwise select DATA

EX2DATA SEGMENT DATA

RSEG EX2DATA

VARIA: DS 1
; Reserve 1 byte in DATA ;
relocatable area

ENDIF

CSEG
; The absolute code segment

JMP START

ORG 13H

; Interrupt IE1 starts at address 13H

JMP EX1INTERRUPT

RSEG EXCODE
; Code from here is relocatable

START: ; Main program


PAS51 81
________________________________________________________

SETB EA
; Initialization of interrupt

SETB EX1

IF INEXT

MOV DPTR,#VARIA
MOV A,#0
MOVX @DPTR,A

LOOP:

MOVX A,@DPTR
MOV P1,A
SJMP LOOP

ELSE

MOV VARIA,#0
; Initialization of a variable

LOOP:

MOV P1,VARIA
SJMP LOOP

ENDIF

END
82 SYSTEM51
________________________________________________________

The last example is using the MACRO and LIBRARY facilities of the
assembler.

; Example 3

GLOBAL_C GSET 0

; GSET will be 0 in both THIS_MODULE


; and THAT_MODULE

LIBRARY THIS_MODULE
; THIS_MODULE will only be loaded
; if THIS_ENTRY is declared EXTRN

PUBLIC THIS_ENTRY
; in a preveously loaded module

EXTRN XDATA( ADDRA, ADDRB )


; Two external addresses

MYMACRO MACRO PA,PB


; Defines a macro with 2 parameters

MOV DPTR,#PA
; Actual PA must be XDATA address

MOVX A,@DPTR
MOV PB,A
; Actual PB must be register or DATA

ENDM

THIS_CSEG SEGMENT CODE

RSEG THIS_CSEG
PAS51 83
________________________________________________________

THIS_ENTRY:
; In here if loaded and called
MYMACRO ADDRA+5*4,R3
; XDATA byte to register R3

MYMACRO ADDRB,P1
; XDATA byte to port P1
RET

ENDLIB

LIBRARY THAT_MODULE
; Next module in same text file

PUBLIC ...

...

ENDLIB
; End of module THAT_MODULE

END
84 SYSTEM51
________________________________________________________

10. The Linker LINK51.

The linker LINK51 will link and relocate object files generated by
SYS51C, PAS51W or ASM51. It will connect externals in one module
with code addresses in others. It may be invoked from the IDE menu
Compile|Link (Ctrl+L). After a succesful Compiler|Make or
Compiler|Build, an automatic linking process will take place.

The main files generated by the linker is a .A51 file which is an INTEL
compatible absolute file, and a .MAP file, an INTEL compatible map
file. If the option is set, it will generate an INTEL HEX format output
file. Also, if that option is set, it will generate an IAR UBROF .UBR
absolute file.

If Ctrl+L is used, a dialog box will appear. The format of what to enter
is the following:

{ -switches} mainfile{ objfiles}[ -H] [ -U]

where switches are one of the letters O, X, or D for the (relocatable)


memories CODE XDATA or DATA, immediately followed by an
address (in hex). The switch can also be M-, in which case no .MAP
file will be generated.

Mainfile and objfiles are names of relocatable, possibly library files,


and default extension .OBJ need not be written. Mainfile will also be
the name of the resulting files with extension .A51, .MAP, and .HEX.

If -H is given, the .HEX file will be generated.

If -U is given, the .UBR file will be generated.

The -O directive will start placing relocatable code from origin <hex
number>.

A -M- directive may optionally be given in the link line. This will
exclude generation of a .MAP file.
PAS51 85
________________________________________________________

If your command line is too long, or you want to repeat the same long
line many times, you may use command file indirection. Place your
linker .OBJ file names and switches in a file, let us say LOADFILE,
with one name or switch on each line, and then enter in the linker
dialog box @LOADFILE or the integrated system compiler directive
#pragma link @LOADFILE

A variant of the LOADFILE is the make project file .KPR. Seen from
the linker, it works as a LOADFILE, but contains HLL extensions and
probably more file names on a line. These are just ignored by the linker.

Concerning assembler translated modules, the default code segment is


CSEG, the absolute code segment. This means that the -O directive will
have no effect unless you define some relocatable named code
segment(s).

The SYS51CW compiler will generate relocatable code modules for


normal code and absolute code for the start- and interrupt jump vector.

Example: Entering into the Compiler|link dialog box

-X2000 PROG1 PROG2 PROG3.LIB CL51 -H

will place the code in the modules PROG1.OBJ, PROG2.OBJ,


PROG3.LIB, and CL51.OBJ from address 0, the relocatable XDATA
addresses will be relocated from location 2000H. All the code will be
placed in the absolute file PROG1.A51 and in the hex- file
PROG1.HEX. A total memory map will be placed in PROG1.MAP

11. The SFR Compiler.

Because so many targets are supported (about 50) and as the different
parts of the system use different source syntaxes for the names of all the
special function registers, a common binary file, SYS51.SFB is used
throughout the system and its compilers, assembler, simulator, and
86 SYSTEM51
________________________________________________________

different emulators. This file describes all the differences between the
targets, and may be changed by you. For this purpose, describing source
files 80xxx.SFR are supported together with a SFR "compiler"
SFR2SFB.EXE. This compiler only works under DOS.

The file SYS51.SFB is a "compiled", binary file that must be placed in


the SYS51W directory together with SYS51W.EXE, SIM51.EXE,
ASM51.EXE, PASCAL.EXE, SYS51C.EXE, and so on. It contains
definitions for different target SFRs.

For you as a user to be able to look at the definitions, and to change


these, source codes for targets are placed in the files *.SFR in directory
\SFR together with a list collection of possible targets in the file
SFR.LST.

Format : SFR2BIN InputProcessor [OutputProcessor] [-switch]

No switch -> Processor.SFR to Processor.SFB


-A -> Alias 1. as 2. in SYS51.SFB
-D -> Delete InputProcessor from SYS51.SFB
-I -> Insert InputProcessor.SFR into SYS51.SFB
-G -> Generate whole SYS51.SFB using SFR.LST

To modify and / or add targets, you may do it following these steps:

1) Change or add a file xxxx.SFR, see syntax below.

2) If a new target is to be added / deleted, modify the file


SFR.LST

3) Run the program SFR2SFB with the parameters:


'8051.SFR -g' in the SFR directory. In the case when there
are more processors in the SFR.LST file than there are .SFR
files answer the question 'Alias processor?' with the nearest
processor you know of, or just 8051.
PAS51 87
________________________________________________________

4) Move the new generated file SYS51.SFB to the .EXE


directory.

The format of the .SFR source files is as follows:

Every line, not starting with a ";", describes a SFR BYTE, BIT,
INTERRUPT routine, or a special characteristic of the particular target
type. The 1. line must be a comment line, describing the processor, as
this line will be presented in the target selection menu.

The syntax is:

<address> <type> <name> [comment]

<address> is a hex number

<type> is either BIT, BYTE, WORD, INTERRUPT, RAMTOP, or


one of the special descriptions: EXTENDED for the Siemens
80517 with extended instruction set, SMALL for the Philips
87751 with limited instruction set, or DALLAS for the
Dallas semiconductor processors that need special code in
DEBUG51.

<name> is the name of the SFR register in (upper-case).

The comment is optional.


88 SYSTEM51
________________________________________________________
PAS51 89
________________________________________________________

P A R T I I , the P A S 5 1 Language

12. The language.

The language PAS51 contains an almost complete implementation of


the language Pascal as defined by N.Wirth in Zurich in 1970. In
addition to that, it contains special features for microcontroller use. The
PAS51 is especially designed for use of the Intel, Siemens, Philips and
Dallas Semiconductor 8051 microcontroller family in embedded
systems, i. e. systems, where the microcontroller is just another
component in some equipment. You will be able to program the 8051
family (i. e. 8051, 8052, 8051FA, 8051GB, 80152, 80C515, 80C517,
80C552, DS80C320, DS5000, 87C751, 89C2051 and about 40 more)
with the aid of PAS51 in both very small applications where the only
memory is internal RAM and/or ROM and in large applications with
lots of external memory. You will be able too, to program applications
where you need concurrency. For users that is used to the pointer
calculation facilities of such languages as PL/M51 and C, the compiler
has been equipped with a switch so this is possible in PAS51, but as you
get familiar with the PAS51 and its code generation efficiency, you will
discover that you do not need calculations on pointers.

Version 6.5 of the compiler offers a automatic multimodule facility


through Units, compatible with the well-known Borland Turbo Pascal
for PC's. Besides this, it also contains object oriented features including
inheritance, similar to that of the same.
90 PAS51
________________________________________________________

13. Basic Symbols.

A PAS51 program consist of a collection of names, numbers, special


symbols and comments. Numbers may be expressed either in decimal
(radix 10), hexadecimal (radix 16) by preceding it by a $ sign or binary
(radix 2) by preceding it by a % sign. Examples of legal numbers are

10 1.05 $A 1E27 126 $FE %10110001

Character and string constants may be written as ASCII letter(s)


surrounded by ' or by the character decimal value preceded by #.
Examples are

'A' 'string constant' #65

Names start with a letter or an underscore followed by letters, digits or


underscores. Although more than 32 characters are allowed, only the
first 32 are significant. There is no difference between capital and lower
case letters. Names may represent keywords, predefined types, ports,
procedures and functions, and user defined types, variables, procedures
and functions. Examples of names are

x bit_y byte While IF Addr SBUF


PAS51 91
________________________________________________________

Special symbols are used for various purposes such as addition and
separation. A list of them with a short explanation is shown in the
following:

+ - * /
are arithmetic and set operators.

< <= = >= > <>


are relational operators.

:= is used to assign expressions to variables.

( ) (. .) [ ]
are different sorts of parentheses, the former are
used in expressions and for procedure parameters,
the latter in conjunction with array addressing.

; is a statement separator.

,: are other separators.

Text between (* and *) or { and } is treated as a comment or a compiler


directive. Compiler directives start with (*$ or {$. A list of those are
given in section 6. Examples are

{ This is a normal comment *)


(*$M $2000 $3000 This is a compiler directive for memory
assignment *)
92 PAS51
________________________________________________________

14. Basic Data Structuring.

All variables in PAS51 must be declared before use. They may be of a


predeclared type or you may declare your own variable types. The
reason why types are necessary is 1) to tell the compiler which
operations are allowed on which operators and 2) to provide you with a
tool to distinguish between your items of different types.

14.1.1 Unstructured types.

Unstructured types represents bits or bytes in the microcontroller.


The built-in type BOOLEAN is a one bit variable represented by the
8051 boolean structure if declared as a variable. If element in an array
or a record, BOOLEAN is represented by a byte.

The built-in type BYTE is the type used for simple integer arithmetic
calculations and general data handling. In respect of addition and
subtraction, bytes are treated as numbers between 0 and 255. As calcu-
lations in the 8051 microcontroller are in 2's complement, you may in
very special cases treat bytes between 128 and 255 as the negative
numbers -128 downto -1, but this is not the case in multiplications,
divisions and by comparing bytes. The byte type take advantage of the
hardware byte-oriented facilities of the 8051 family chips.

The built-in type CHAR represents ASCII (or other national ISO
alphabet) characters.

The built-in type INTEGER represents a 16 bit signed type with a


number range from -32768 to +32767

The built-in type WORD represents a 16 bit unsigned type with a


number range from 0 to 65535.
PAS51 93
________________________________________________________

The built-in type LONGINT represents a 32 bit signed type with a


number range from -2147483648 to +2147483647

The built-in type REAL represents a 32 bit floating point type with a 24
bit mantissa and bit exponent according to IEEE 794.

The built-in type PROCESS may be used in conjunction with the low
level concurrency primitives NEWPROCESS and TRANSFER as
explained in chapter 21.

Besides the built-in types you may declare your own types in a type
declaration part. This part will start with the reserved word TYPE.

An enumeration is a user declared unstructured type that consists of a


collection of named constants belonging exclusively to that type. May
be declared in the following way:

TYPE
valve_position=(open,closed,opening,closing);

The subrange type is another user-definable type that defines a new type
consisting of a part of the number range of a whole longint, integer,
byte or char. Examples are

TYPE
digit = 0..9 ;
letter = 'A'..'Z' ;

14.1.2 Structured types.

In PAS51 you have different type of structured types.

The ARRAY consists of a ordered collection of one unstructured or


structured type. Arrays in PAS51 are 1 or multi-dimensional. An array
type is declared with the subscript being a subrange. The subscript of
94 PAS51
________________________________________________________

the array may be surrounded by either [] or (..). 1. dimensional arrays


are implemented exactly as in standard pascal, whereas multi-
dimensional arrays are declared in this way: ARRAY[min1..max1] of
ARRAY[min2..max2] of ... .

All arrays are used as in standard pascal.

Examples:

TYPE
arr = array[ 5..4*2 ] of byte ;
sl = 0..79 ;
line = array(. sl .) of char ;

The RECORD consists of a collection of different types of unstructured


or structured types. It is defined by the reserved word RECORD
followed by definition of the fields and ended by the word END. An
field of a record is referenced by the record name, a dot (.) and the
name of the field. An example:

TYPE
rec=RECORD
x,y: byte;
alfa: array[0..10] of char
end;

You may declare any combination of arrays of records or records of


arrays, but there is a size limit: no single record may be larger than 256
bytes in total.

Another construct very much like the record construct exist: Numbered
bits on special registers and ports. This construct is identically to the
same facility in the Intel 8051 Assembler Language.

Example: p1.5
PAS51 95
________________________________________________________

The OBJECT type consists like the record of a collection of different


types of variables, but contains in addition METHODs (object functions
or procedures) that acts on the data part of the object, see chapter 20.

The STRING type acts very much like ARRAY of CHAR, but the first
byte is dynamically showing the length of the text string.

The POINTER type will be treated in chapter 18.

The SET type consists of a set of some elements that you define. In
PAS51, variable sets are restricted to one byte; You may think of the set
as each individual of the 8 bits in the byte representing one element of
the set, a one value of the bit expressing that element to be member of
the set. SETs will be further explained in chapter 19.
96 PAS51
________________________________________________________

14.2 Variables.

All non-predefined variables must be declared before use. This is done


in the VAR part of your program. This part starts with the reserved
word VAR. A variable may be of any unstructured or structured,
build-in or user defined type. The variable may be placed in the internal
RAM of the 8051 (if no external memory present or using the predicate
DATA or IDATA if external memory is present) or in the external
RAM (default if present, or use the predicate XDATA ). Examples:

VAR
count: byte;
ch1, ch2: char;
char_buffer: array(. 0..79 .) of char xdata;
line1, line2: line xdata;
valve1, valve2: valve_position;
PAS51 97
________________________________________________________

14.2.1 Predefined variables.

Special function registers in the 8051 are given special names. Those
names will normally be the same as in the appropriate company's
assembler language. For exact knowledge please refer to the xxx.SFR
definition files.

For declarations of internal variables at fixed addresses >127 the


following is true: The declaration XX: byte at 200; will result in
reserving a variable in the indirectly addressable RAM area in
processors like 8052 and 80515, whereas the declaration SBUF: byte
SFR AT $99 will result in the (already existing) declaration of the
special function register SBUF.

There are 2 predefined arrays in the language.

XMEM defines an array of bytes in the XDATA memory, starting at


XDATA absolute 0.

CMEM defines an array of bytes in the CODE memory, starting at


CODE absolute 0.

Both arrays are 64KBytes long.

14.2.2 Absolute placed Variables.

Sometimes it may be necessary to place variables at some absolute


address denoted by an address or a variable name. By using the
predicate AT or ABSOLUTE, this is made possible.

Examples:
98 PAS51
________________________________________________________

VAR
R2_0: byte absolute $2;
C_8155: byte xdata absolute $3800;
doubleR2_0: byte absolute R2_0;

NOTE: Unlike some other systems, no reservation of the memory


position is performed, ie. you may deliberately or by mistake
place the variable at the same memory location as another
variable.

14.3 Named Constants.

For convenience and sometimes code compactness, it is possible to


name unstructured and structured constants. This must be done in the
CONST part of a block as in the following examples:

TYPE
arr= array(.0..3.) of integer;

CONST
Pipe=5*5;
Pipe1=Pipe+1;
cstring='This is a constant text string';
constarray: arr=(1,22,1235,-40);
cstringarray: array[1..2] of string[15]=
('Text 1',
'and text 2');

Three predefined named constants already exists, TRUE, FALSE and


NIL.
PAS51 99
________________________________________________________

15. Statement part.

The statement part of a PAS51 program is composed of basic data


manipulating actions such as assignment, conditions, loops, input and
output of data values.

15.1 Assignment.

In PAS51 an assignment of a value to a variable of any type is denoted


by

variable:=expression

where the expression is composed from variable and constant operands


when appropriate using familiar operators such as +, -, *, / div, mod
etc. (The full range of operands appropriate to various types of data
values is discussed more fully in subsequent sections.) Note that it is
possible to assign whole arrays or records in one statement. It is
possible to assign an integer to a byte or subrange variable, or a longint
to an integer, word or byte variable; automatic type conversion will take
place. Simple examples of assignment statements are

i:=7

bitx:=true

count:=count+1

record1.array1:=record2.array1
100 PAS51
________________________________________________________

record1:=record2

P1:=%11010110

15.2 Input and Output.

Input and output in PAS51 are based on the built-in ports and timers of
the 8051. Ports as P0 to P3 (P0 to P5 in 80515) and SBUF are treated as
output ports just as variables in assignment statements like the above,
whereas as input ports in parts of expressions. Simple examples of
input and output are

p1:=$27

serial:=sbuf

bit_y:=p2.3

Microcontrollers connected to a terminal or another computer may use


the higher level constructs write, writeln, read readln.

Values v1,v2,... may be written to some form of display or printer by a


statement of the form

write(v1,v2,...) or write (d,v1,v2,...)

Subsequent alignment of the output file at the start of a new line may be
achieved by using the alternative form

writeln(v1,v2,...) or writeln(d,v1,v2,...)

or by subsequent use of the form

writeln or writeln(d)
PAS51 101
________________________________________________________

V1, v2 ... may or may not be formatted. Formatting follows standard


Pascal: ":" followed by an expression will put in so many blanks before
a number or string that the whole field will fill the value of the
expression. In case of REAL numbers, a second ":" followed by an
expression may follow. This indicates the number of digits after the
decimal point. Concerning the latter: Version 1.xx and 2.xx uses a
different approch for writing REAL expressions: no formatting and a
standard setting of the decimal point. This gives a much faster and less
code consuming procedure. Therefore you have the option to change
your file FP51.OBJ to the old-like write REAL code by copying the file
FP51S.OBJ to the file FP51.OBJ.

Values may be read from some device or text file d to variables v1, v2,
... by using the

read(d,v1,v2,...) or read(v1,v2,...)

When using devices, not text files, the

readln(v1,v2,...) or readln(v1,v2,...)

is identical with

read(d,v1,v2,...) ; writeln(d)

(NOTE this is NOT identical with standard pascal: no eoln or eof flags
exist when using devices)
102 PAS51
________________________________________________________

The d denotes device name or a text file. Available devices are


INPUT: or
OUTPUT: or
SERIAL: The SBUF serial device of the 8051.
(The S0BUF serial device of the 80C517 and
80C320, also SERIAL0)
DISPLAY: An alphanumeric display connected to an external
memory address. (WRITE(LN) only)
SOFT: A software UART using one port bit.
USER1: A user definable device.
USER2: One more user definable device.
SERIAL1 (80C517 series and DS 80C320 only) The S1BUF
serial device.

Default (i.e. without the d) is SERIAL.

The SERIAL device must be initialized before use to the correct baud
rate and bit length by the call

RESET;

or the identical

RESET(SERIAL);

In this version of the compiler, you may use general text files. However,
to gain full use of text files, you must either buy the optional FILES
TOOLBOX or taylor your own version of the file IODRIVER.ASM, see
appendix C.

In case of using general TEXT files, you have to use further


declarations, procedures and functions.

Declarations:
PAS51 103
________________________________________________________

f1[,f2,...]: text; (* defines f1,f2,... as text files *)

No ARRAY[ ... ] of TEXT or record types containing TEXT may be


used.

New procedures:

ASSIGN(f,<dos file name>);

ASSIGN will connect the text file f with a dos file name given in the
string <dos file name>.

RESET(f);

RESET will reset the file f to the start of the file. May thereafter be used
for input or output.

REWRITE(f);

If and old file by the name assigned to f is found, it will be erased. After
that, a file of initial length 0 will be created. Writing to f is after that
supposed.

CLOSE(f);

The file f is closed.

New functions:

EOLN(f);

This boolean function will return the value TRUE if the you have
reached end of line by preveous READ(f,...)s. May be set to FALSE by
READLN(f,...);

EOF(f);
104 PAS51
________________________________________________________

This boolean function will return the value TRUE if if you have reached
end of file by preveous READ(f,...) or READLN(f,...).

Examples of high level I/O are

writeln(display,'This is the number 3: ':30,2+1)

read(i)

assign(textfile1,'MYFILE.TXT');

reset(textfile1);

while eoln(textfile1) do readln(textfile1);

The serial channel is not preprogrammed for communication or


baud-rate, so this has to be done in the program before using write or
writeln, read or readln: Place a RESET or RESET(serial) statement in
your program before using the SERIAL device. On how to design your
own low level character output driver, please refer to appendix C.
PAS51 105
________________________________________________________

15.3 Sequential composition.

The sequential execution of number of actions A, B, C,..., can be


written in sequential text simply as the actions separated by ;

A;B;C; ...

When the composite action is to be regarded as a single component of


some larger structure, brackets such as begin ... end may be introduced:

begin A ; B ; C ; D end

often written as

begin
A;
B;
C;
D
end
106 PAS51
________________________________________________________

15.4 Selection.

15.4.1 If Statement.

Selection between two alternative actions A,B on some conditions Q,


can be written in sequential text as

if Q then A else B

More complex selections can always be expressed as a combination of if


... then ... else constructs probably in conjunction with the begin end
construct. Two special cases may be singled out for special notation, as
in Pascal

(a) when one of the alternative actions is null the


reduced form

if Q then A

may be used;
PAS51 107
________________________________________________________

15.4.2 Case Statement.

(b) when selection between a set of actions A, B, C, ...


has to be made according to corresponding values
a,b,c,... of some selector expression Q the case
notation may be used, viz.:

case Q of
a :A;
b,c : BC ;
d :D;
end

The selector expression must be of a scalar type: byte, char, word,


integer or enumeration.

If none of the selectors are equal to the current value of the selector
expression, this version will produce no action. If, however you want to
have this opportunity, an optional else action may be taken as shown
below:

case Q of
a:A;
b:B;
c:C
else D ;
end

It is also possible to use a subrange of constants as the selector.

case Q of
a..b: AB;
c..f: CDEF;
else G;
end;
108 PAS51
________________________________________________________

The CASE construct is a standard pascal construct. In PAS51, it is


alternatively possible to use the EXEC procedure for executing
selections of code. See chapter 16.6. The EXEC procedure is normally
working faster than the CASE construct, but may be more dangerous.

15.5 Repetition.

15.5.1 While Statement.

Repetition of some action A while some condition Q remains true can


be written in sequential text as

while Q do A

15.5.2 Repeat Statement.

If the action must be performed at least once, it may be convenient to


use the alternative form

repeat A until not Q


PAS51 109
________________________________________________________

15.5.3 For Statement.

When the number of iterations is known at the start of repetition, and


perhaps a corresponding counting variable is required, the constructs

for v :=i to f do A
for v :=i downto f do A

may be used. These cause the action A to be repeatedly executed while


variable v takes successive (ascending or descending) values from
initial value i to final value f. The variable v must be a simple variable
of any ordinal type except boolean. The final value f will be evaluated
as an expression.

For code and speed efficiency, use variables declared DATA or IDATA
as counter variable v.

A special situation arises when f is a variable or contains a variable


which is changed in the inner part of A. This may cause unpredictable
results and must therefore be avoided. The value of the step variable
outside the for loop is undefined.
110 PAS51
________________________________________________________

15.6 The WITH statement.

The WITH statement allows you to gather referencing fields in a certain


record or object to only mentioning the same object once within a block.
This is done using the WITH statement.

The syntax of the with statement is the following:

"WITH" record-name {"," record-name } "DO" statement.

Normally statement is a compound statement, so that repeating the


record-name is omitted. Every time a field name from one of the objects
mentioned in 'record-name' is met, the compiler adds the full variable
or method name. In many cases, this may lead to not only less writing
but also to less code.

Examples:

VAR
Rec: RECORD
X,Y: Integer;
Ch: Char;
END;

BEGIN
WITH Rec DO BEGIN
X:=0;
Y:=P1;
Ch:=Chr(SBUF);
END;

TYPE
PObj=^TObj;
TObj=OBJECT
PAS51 111
________________________________________________________

X1,Y1: Integer;
CONSTRUCTOR Init;
PROCEDURE DoThis;
PROCEDURE DoThat;
END;
VAR
Obj: PObj;

BEGIN
Obj:=New(PObj,Init);
WITH Obj^ DO BEGIN
DoThis;
IF X1=5 THEN
DoThat;
END;

15.7 Combining the Constructs.

The above given statement constructs may be combined at will.


Examples of this may look like

while not scon.5 do (* wait for serial input *);


if ch>=' ' then
begin
sbuf:=ch; (* send visual character *)
ch:=chr(0) (* make it invisible *)
end
else
while...do...
112 PAS51
________________________________________________________

15.8 Embedded code.

If you want to include simple assembler statements in your PAS51


program, this may be done in different ways.In a CODE statement this
is done at an absolute hex level. If bigger and/or more complicated
inclusions are necessary, modify the generated assembler code, and use
the assembler and linker to assemble and link it.

The Code statement consists of the reserved word CODE followed by


the values of code bytes, separated by spaces or newlines. You may
express the code bytes in terms of 1) numbers, 2) named constants or 3)
addresses represented by the name of a variable or a procedure. Due to
the ambiguity in function representation, the reference to functions is
not allowed. In case 3), the following rules on the length (1 byte or 2
bytes) may apply: If the name represents an 8 bit entity (a name of an
internal RAM variable), 1 byte, else 2 bytes.

Examples:

var
alfa: integer idata;
beta: byte xdata;

const
movad=$E5;
movdptr=$90;

begin
code
movad alfa
movdptr beta
$F0 { MOV @DPTR,A } ;
...
PAS51 113
________________________________________________________

15.9 GOTO in PAS51.

Although it is not normally recommended, it is possible in a very


restricted way to use direct program jumps. Not more than one label per
block may be declared by a label declaration. Such a label must be an
integer. The statement GOTO may then be used throughout that block
to jump to the label. It is not possible to jump out of a block with the
use of high level constructs. The only case where GOTO may be
convenient is jumping away from an unusual condition (error
condition), in all other cases, You will find that the above shown
structured constructs are easier to understand, easier to use and easier
get working correctly.

16. Expressions and calculation rules.

All types may be assigned to variables of the same type. They may also
be compared to variables or constants of the same type. The result of a
comparison will be of the type boolean.
Integers or bytes may be variables declared integer, byte, constants or
elements of variables or constants declared as array(. ... .) of integer or
byte. They may be part of expressions containing arithmetic or logical
operators. The operator hierarchy is as follows:

First solved: shr shl and * div / mod


or xor + -
Last solved: > >= = <= < <>
114 PAS51
________________________________________________________

Table of operations and results:

Operation Operators Result

and Boolean Boolean


and shr shl Byte Byte
* div mod Byte Byte
*/+- Real Real
/ Byte Real
/ Word Real
/ Integer Real
/ Longint Real
* div mod Integer Integer
and shl shr Integer Integer
* div mod Word Word
and shl shr Word Word
* div mod Longint Longint
and shl shr Longint Longint
or Boolean Boolean
or xor + - Byte Byte
or + - Word Word
or + - Integer Integer
+- Longint Longint
+ String String
= <> any type Boolean
> >= >= < Byte Boolean
> >= >= < Word Boolean
> >= >= < Integer Boolean
> >= >= < Longint Boolean
> >= >= < Real Boolean
> >= >= < String Boolean
PAS51 115
________________________________________________________

If one of the operands is integer, word or longint and the other byte,
automatic type conversion to integer, word or longint takes place. In
other cases, automatic conversion may take place, but if you get an
incompatible types error message or you use the $T- directive, you may
use the general type cast function of the compiler.

If one of the operands is real and the other byte, word, integer or
longint, automatic type conversion to real takes place.

If the operator is + and the operands string then string concatenation


will take place. If you haven't declared an external data RAM memory
(no $M directive or $M xxxx -1 directive) the dynamic length of the
resulting string can't exceed 15. With external RAM, the maximum
resulting string length can't exceed 80.

Examples:
a := i + j * 3 ;

b := ( arr(. i+3 .) - 25 ) div 4 ;

if (valve1<>valve2) and (valve2=closed) then ...

NOTE:
You must remember that bytes are
0..255, but in 2's complement. This
implies that for instance the program
part (a and b are of the type byte)

a:=2;
b:=(a-4) div 2

will set b to 127, not -1. ( Please study this carefully )

You may overcome this problem by setting the compiler directive


{$F+} or by using integers instead, but be aware of the following: The
116 PAS51
________________________________________________________

8051 chip family is designed especially for 8 bit use; for instance it is
equipped with a very fast unsigned 8 bit division (4 microseconds at
12MHz clock) that cannot at all be used for 16 bit division. So if you
want to write fast and compact programs, use bytes as much as possible
throughout your program, integers only if absolutely necessary.

To help you to mix bytes and integers and get the correct result
anyhow, 3 conversion functions are offered.

The INT function requires a byte expression as the parameter and will
return the corresponding 16 bit signed integer value.

The HI and LO functions takes an integer expression as their


parameters, and return the upper or lower 8 bit part of those integers or
words.

Examples:

var
i,j: integer;
c,d: byte;
begin
i:=int(c)*int(25);
d:=hi(j);

...
PAS51 117
________________________________________________________

17. Procedures and Functions.

A block consists of a label, type, constant, variable and procedure


declaration part followed by a statement part embraced between BEGIN
and END .

The whole program is a block ended by a . (dot). The block may also be
the body of the subroutine constructs in PAS51, procedures and
functions.

17.1 Procedures.

The declaration of a procedure consists of a block preceded by a


heading which associates a name with the block. A procedure may be
invoked in the statement part by just giving that name. Example of a
procedure declaration and use:

var
item_count: byte;

procedure count_item;
begin (* block of count_item has only statement
part *)
item_count:=item_count+1
end;

begin (* main part *)


item_count:=0;

...

count_item;

...
118 PAS51
________________________________________________________

end.

17.2 Value parameters.

It is often adequate to let a procedure work on values, given at run time.


Such values may be given to the procedure as a (value) parameter.
Example: By declaring a procedure

Procedure write_char( ch: char);


begin
while not ti do; { wait until the bit flag ti goes on }
sbuf:=ch;
ti:=false
end;

and by supplying a corresponding actual parameter in the call of the


procedure

...;write_char('a') ; ...

When the procedure is called, a variable ch is created, corresponding to


the formal parameter, and is assigned the value of the corresponding
actual parameter (here 'a'), which may be any expression that yields a
value of type char. An actual parameter such as this, that must yield a
value, is called a value parameter.
PAS51 119
________________________________________________________

17.3 Variable Parameters.

Sometimes it is convenient that a result of an operation in a procedure


be returned to the block, from which it was invoked; such a parameter
is called a variable parameter. The declaration of the corresponding
formal parameter is prefaced by the word VAR as in the following
example.

procedure get_char (var ch: char) ;


begin
while not ri do ; (* wait *)
ri:=false;
ch := sbuf
end

When the procedure is called,

...; Get_char(line(.i.)) ; ...

all operations referring to ch within the procedure actually operate on


the variable Line(.i.) - in this case the actual parameter must be a
variable of type char.

NOTE. VAR specified formal and actual parameters must


reside in the same sort of memory, i. e. both
internal DATA, both internal IDATA or both
external XDATA memory. Formal parameters are
the ones you specify in the procedure (or function)
head, whereas actual parameters are those with
which you call the procedure (or function). VAR
specified parameters can't be of type BOOLEAN
except as record fields or array members, because
the boolean processor of the 8051 family don't
allow runtime calculation of such addresses.
120 PAS51
________________________________________________________

17.4 Functions.

In the last example, you must have a whole statement to get a new
value of line(.i.). If instead you prefer to get the next input character as
a part of an expression, you might have used a function instead:

function read_char: char ;


begin
while ( scon and $1 ) = 0 do ;
ri:=false;
read_char := sbuf
end

The function is called by using its name as an operand in an expression,


e.g.

... ; line(.i.):=read_char ...;

Evaluation of an expression containing a function call causes the


function block to be executed. The value assigned to the function name
during this execution is then used as the corresponding operand value
in the expression evaluation. Functions, like procedures, may have
parameters.
PAS51 121
________________________________________________________

17.5 Scopes and Recursivity.

17.5.1 Scopes.

Names of variables, types, constants, functions and procedures are only


visible in the block, where they are directly defined or indirectly
because they are defined in an outer block to the current block. For
instance all variables defined in the non- subroutine block will be
visible anywhere in the program, whereas a variable I defined in a
procedure X will not be visible in an other procedure Y, defined in the
same block as X. It is allowed, but not recommended, to use the same
name for different variables in different blocks. If you, however, use the
symbolic features of the System51 simulator or emulators, don't use the
same name twice unless you want to get into trouble.
122 PAS51
________________________________________________________

17.5.2 Recursivity.

For code efficiency reasons, PAS51 by default doesn't support


recursivity. In this default situation, you must not let a procedure call
itself neither directly nor indirectly. Although it isn't forbidden to do
recursive calls, variables and parameters are placed in absolute
locations, so you will run into trouble if you use such without extreme
precaution.

By setting the compiler directive {$R+ [<n>]}, you allow recursion


(and by some precautions, also reentrancy) to take place. The {$R
directive can only be set if you use the large model, i.e. if you have used
the {$M directive to set xdata.

In case of recursivity, the parameters and local variables of procedures


and functions are placed in xdata, relative to a build-in (data placed)
public pointer variable called ?FRAMEPTR.

The <n> in the {$R directive is a number, used to tell (in 256 bytes
pages) the system, how much xdata space you want to be used in total
for parameter- and local variable space. Default is 1 KByte (<n>=4).
PAS51 123
________________________________________________________

17.6 Predefined procedures and functions.

Some procedures and functions are already to your disposition.

Ord(v):integer The function ord will return the (integer) value of


any variable that is represented by one or two bytes
in the controller. Examples:

byt := ord( 'A' ) ;

byt1 := ord( valve1 ) ;

Chr(v):char The function chr will return the (char) value of an


ordinal expression. Example:

ch := chr( $31 )

Addr(v) The function addr will return the (word) address of


a variable or a procedure. It is not possible from a
running program to decide, whether a variable is
situated in external or internal memory, or
whether a name is a variable name or a procedure
name.

Length(s):byte The function length will return the dynamic length


of a string variable s.

Hi(i):byte The function HI will return the byte value of the


upper 8 bits of an integer or word. This is not the
same as dividing an integer by 256 due to the sign
bit.
124 PAS51
________________________________________________________

Lo(i):byte The function LO will return the byte value of the


lower 8 bits of an integer or word. This is not the
same as assigning an integer to a byte or taking
the modulo 256 value due to the sign differences
between bytes and integers.

Int(b):integer The function INT will return an integer value of a


byte considered a 2's complement 8 bit entity.

Float(v):real The function FLOAT will return a real value of a


byte or integer. May be used to force early type
conversion.

Trunc(r): integer The function TRUNC will return an integer value


of a real by truncation. The result is of type INTE-
GER. If you want to convert a real to longint, use
the general typecast possibility, i.e. LONGINT(<-
real_type_expression>)

Round(v): t The function ROUND will return the nearest


integer value of a real. The result is of type
INTEGER.

Abs(v): t This function will return the absolute (positive)


value of an integer, longint or real expression

Val(s,v,hj) The procedure will convert a string to an integer


or real. S is a text string, v is a real or integer
variable and hj is a byte that will contain the add-
ress index of the position of the terminator in the
string after the conversion.
PAS51 125
________________________________________________________

Str(v,s) This procedure will convert a word, integer,


longint or real v to string s. It has the form STR-
(v,s) where v is a real, integer or word expression
and s is a text string. Like in write statements, v
may be formatted with 1 or 2 ':' followed by
numbers.

Exit Placed in a (non interrupt) procedure or function,


this predefined procedure will cause an immediate
return from the procedure or function. Do not
place an EXIT in the main program or in an
interrupt procedure, as this would result in an
unpredictable program flow.

Exec(w) This procedure will call a procedure, whose


address is contained in a (word or integer) variable
w. For instance EXEC ( AVAR[I] ) will execute
the procedure code, whose address is contained in
the I'th element of array AVAR. May be used as a
fast alternative to the CASE construct.

Inc(b) This procedure increments a scalar variable b by 1.

Dec(b) This procedure decrements a scalar variable b by


1.

HighNib(b): Byte; will return the high 4 bits of b, swapped into the
low 4 bits of the result; the high 4 bits are zeroed.

LowNib(b): Byte; will return the 4 msb of b zeroed.

NibToByte(b1,b2): Byte; will return the result b1 shl 4 + b2.


126 PAS51
________________________________________________________

The following transcendental functions all uses the floating point


package and are therefore not reentrant. Please notice that they
therefore cannot be use in interrupt routines.

SQR The square of the (real) argument.

SQRT The square root of the argument.

EXP The exponential function e.

LN The (natural) logarithm of an argument.

COS
SIN
TAN The trigonometic functions are calculated by row
expansion and are therefore accurate, but not
extremely fast.

ARCTAN The result of arcus tangens ARCTAN takes values


from -pi/2 to +pi/2 as normal in math, not 0 to pi
as specified in standard pascal.
PAS51 127
________________________________________________________

The following 2 port handling routines takes care of processor


dependant I/O port problem. Normally, ports in expressions are input
ports and ports on the left side of assignments are output ports. When
you, however, uses a port mixed, i. e. some bits for input and some bits
from the same port for output, you may need to read the output latches
instead of the input pins. In assembler, two special instructions are
present for this purpose, ANL Px,A and ORL Px,a.

PORT_AND(PORT,BYTE)
will read the output latches of PORT, do
an AND operation between this value
and a BYTE expression, and finally
output the result to PORT.

PORT_OR(PORT,BYTE)
will read the output latches of PORT, do
an OR operation between this value and
a BYTE expression, and finally output
the result to PORT.

Examples:

Let Ix be an integer variable and Bx a byte variable.

Bx:=253; Ix:=bx; { Ix will be set to 253 }

Bx:=253; Ix:=INT(Bx) ; { Ix will be set to -3 (=11111101B) }

Bx:=100; Ix:=Bx*10; { Ix will be set to 232 (=1000 mod 256) }

Bx:=100; Ix:=INT(Bx)*10; { Ix will be set to 1000 }


128 PAS51
________________________________________________________

17.7 The general typecast function.

A general tool, looking very much like the built-in functions is the
general typecast possibility.

The name of a type, for instance WORD or a user defined type might be
used as a "function" name, followed by a parantetized expression of
another type. The result of such a "function" will be conversion of the
type of the expression to an expression of the named type. Conversion
is possible following certain rules: a) All types of the same length may
be converted. b) conversions between any of the types BYTE,
INTEGER, WORD, LONGINT and REAL may be performed. When
converting from REAL, truncation is used.
PAS51 129
________________________________________________________

17.8 Interrupt procedures.

The same interrupts as the hardware support are supported by the


PAS51 language as special procedures with predefined names and
blocks you are supposed to program. The compiler will automatically
insert the necessary code to switch current bank and to save special
registers like the acc, psw and b registers used in the interrupt routine.

The syntax of an interrupt procedure is:

PROCEDURE INTERRUPT <interrupt routine name>; [ USING n; ]

or

PROCEDURE INTERRUPT <interrupt routine name>


(name_of_block); USING 0;

n denotes the bank number used, n=1, 2 or 3. Default is 2

Possible <interrupt routine name>s are

8031, 8x51, DS5000, 805x2, 80x21:

SERIAL TIMER0 TIMER1 INT0 INT1

8x52:

SERIAL TIMER0 TIMER1 INT0 INT1 TIMER2

805x5, C515:

SERIAL TIMER0 TIMER1 INT0 INT1 TIMER2 IADC IEX2 IEX3


IEX4 IEX5 IEX6.
130 PAS51
________________________________________________________

8xC552:

X0 X1 T0 T1 S0 S1 CT0 CT1 CT2 CT3 ADC CM0 CM1 CM2 T2

87C751:

X0 X1 T0 T1 S1

Both fast and slow interrupts are implemented.

When using bank 1 to 3, the fast bank switching is used. Such interrupt
routines cannot use operations on variables and constants of type REAL
or LONGINT or string concatenation. At 12MHz clock rate, it takes
about 10 microseconds to enter or leave interrupt.

Using bank 0 for interrupts causes a slow interrupt to take place. Slow
interrupt can only take place if you have an XDATA memory in your
system. In this case, not only bank 0, but floating point- and longint
registers are moved to and from XDATA memory. It will take
(@12MHz clock) about 200 microseconds to enter or leave the
interrupt, ie. 400 plus interrupt routine code in total.
The built-in transcendental functions like SIN and LN and read and
write procedures and STR and VAL are not reentrant and uses its own
data area, which is not moved away on slow interrupts. Those functions
may therefore not be used in any interrupts.

The name_of_block variable, mandatory in a slow interrupt declaration


must specify a name of an XDATA placed array, at least 30 bytes long.
The interrupt entry and leave code will use this XDATA area as a
scratch pad area for bank 0 and the floating point registers.

The fast and slow interrupt has nothing to do with the priority systems
of the processors. It is up to you to program that.
PAS51 131
________________________________________________________

NOTICE 1:
When using bank 1 to 3 fast interrupt, it is not
permitted to share routines between interrupt and
non- interrupt part of a program. If you want to
share a procedure or function between more
interrupt procedures or place such routines
elsewhere, you may set the bank used for code
generation by the USING attribute to procedures
or functions. PROCEDURE iii; USING n, where
n=1, 2 or 3 will define a procedure to be called
from interrupt procedures, whereas PROCEDURE
ppp; USING 0 will define a normal procedure.
USING is only necessary when changing format.
Used in connection with a normal procedure/func-
tion, USING is a toggle switch.

NOTICE 2:
The runtime package for LONGINT, REAL and
STRING-addition uses 2 fixed address registers
and bank 0. It is therefore not possible to use
longint and real operations and string addition
inside fast interrupt routines.

NOTICE 3:
When working with a multimodule program, you
must know that only the MAIN module
("PROGRAM" module) will generate the interrupt
vector. At least the head of all interrupt procedures
must be placed in that module. If you want to
place (most of) the body in another module, you
must define an imported procedure, called from
within the procedure interrupt xxx; Remember the
USING n statement part.
132 PAS51
________________________________________________________

You may use one interrupt routine as an interrupt routine for another
interrupt without loosing time to call a common procedure. The syntax
is:

PROCEDURE INTERRUPT i1; AT i0;

The interrupt routine i0 must be defined before this statement, defining


i1. Also, both i0 and i1 must be defined in the same module.

You may reduce the code and stack space used for pushing and popping
information at interrupt entry/exit by using the new compiler directive
(*$ISn*), that controls the level of PUSHING / POPPING; the possible
values of n are:

4=Save PSW,(& swBank) ACC,B,DPTR <default & safest)

3=Save PSW,(& swBank) ACC,B

2=Save PSW,(& swBank) ACC

1=Save PSW,(& swBank)

0=Save nothing

Use only if interrupt speed is critical, or if stack is at a premium. Use


2,1,0 with extreme care, there is no checking!!!
PAS51 133
________________________________________________________

Example:

program interrupt_demo;

var
timer: word; { counts seconds }
fractions: word;

procedure interrupt timer0;


begin
inc(fractions);
if fractions=4000 then
begin
inc(timer);
fractions:=0
end;
TF0:=false { end this timer-interrupt }
end;

begin { initialization of timer and timer0 }


timer:=0;
fractions:=0;
TR0:=true { enable timer0 }
ET0:=true; { enable timer0 interrupts }
TMOD:=2; { Timer0 M1 true: 8 bit auto reload timer }
TH0:=6; { interrupt every 250 microsecond (if 12MHz clock) }
EA:=true; { enable general interrupt }
end.
134 PAS51
________________________________________________________

17.9 External procedures.

You may link pascal programs to procedures written in other languages


in different ways. One way is to use the .ASM file generated by the
compiler and then link those routines with the linker LINK51. Another
way is to declare external procedures in the pascal program at absolute
placed locations. This is done by the declaration

PROCEDURE xx; AT $hhhh;

or with parameter (s)

PROCEDURE yy(param1: byte at $hh; ... ); AT $hhhh;

Although the methods mentioned still are possible, the most commonly
used method in version 2.0 and 3.0 will be to use separately compiled
or assembled modules as mentioned in chapter 20.
PAS51 135
________________________________________________________

18. Pointers.

If your target is equipped with XDATA ram memory (told the compiler
by the M directive) then you may use the pointer type variables either
like in Pascal by using variables on the heap by calls to NEW,
DISPOSE, MARK and RELEASE, or like in C and PL/M by calcula-
ting new pointers.

A pointer to a type (some simple type, array type, record type etc.) is a
mean to access that type in an indirect way through a variable, for
instance p pointing to different points in memory at different times, the
variable pointed to ( named p^ ) being the content of memory, where p
is actually pointing.

Declaration of a pointer type or a pointer variable is done by ^<type>,


where <type> is the type that the pointer is supposed to point at. As it
may be convenient to let the pointer in the record, to which the pointer
points to be the pointer type itself, it is allowed to declare a pointer to a
type not yet declared itself.

Example.

type
p= ^rec;
rec= record
data: integer;
ptr: p
end;
var
p1,p2: p;

p1^.data:= ... { something is done to the field data of the


record rec, which p1 is actually pointing to }
136 PAS51
________________________________________________________

18.1 Pascal-like Use of Pointers.

If you use the normal type-checking {$T+}, the only way of mani-
pulating pointers is to assign a pointer to another pointer of the same
type, or to use one of the three built-in procedures NEW, MARK or
RELEASE.

The (external data) memory is divided into two parts, the fixed address
space for variables declared in the VAR-parts and as procedure
parameters and the HEAP, the rest of free external memory.

A call to NEW(p1) will reserve space on the heap for a variable of size
and type rec, if p1 is of a type ^rec.
A call to MARK(px), where px is any pointer type variable will set px
to the first free position on the heap.
A call to RELEASE(px) will move all heap space from px^ and up to
the free heap space.

Example.

new(p1); { A record rec is placed on the stack }


new(p2); { Another one }
p1^.ptr:=p2; { The first is made pointing to the other }
p2^.ptr:=nil; { A chained list of two records is made }
PAS51 137
________________________________________________________

18.2 C or PL/M type Use of Pointers.

Pascal like languages are strictly type checking languages. If you don't
do anything actively, PAS51 is acting like Pascal. The reason for
strictly type checking is program security: The compiler will tell you if
you are possibly making mistakes in as many contents as possible. This
puts some restrictions on what to do in your program that is unfamiliar
to users of such languages as C and PL/M, where pointers are freely
manipulated. Free manipulations of pointers might lead to more effici-
ent programs, but also to greater danger of programming errors. Before
you read further here, please realize, that one of the reasons for this is
the lack of direct multiple byte assignment in PL/M and C, but here
present as described in chapter 14.

To freely manipulate pointers in PAS51, set the type checking compiler


directive off (*$T-*)

19. Set.

The SET data type is generally restricted to set of up to only 8 potential


elements in the set, such a set will be represented in 1 byte. For
instance, an enumeration of up to 8 names may be made into a set type.
All types of operations may be performed on such a set.

One important extension to this exist. An IN construct, where the set is


a constant, may test sets of a maximum of 256 potential set members.
138 PAS51
________________________________________________________

Examples.

type
bits=(b0,b1,b2,b3,b4);
bitset=set of bits;
var
bits1: bits;
bitset1: bitset;
begin
bits:=b1;
bitset1:=[b0,b2,b4];
if bits in bitset1 then
writeln('This should never occur')
end.
______________________________________
type
bitset=set of 0..7;

timer0_def=(m0,m1,ct,gate);
timer0_bits=set of timer0_def;

var
bitset1: bitset;
i: 0..7;

begin
for i:=0 to 4 do
bitset1:=bitset1+[i];
bitset1:=bitset1-[2];
end.
______________________________________
var
ch: char;
...
if ch in ['0'..'9','A'..'Z','?','_','Æ','Ö','Å'] then ...
PAS51 139
________________________________________________________

20. Objects.

Objects give you the opportunity to use a different way of thinking


when programming. Instead of considering data and programs as two
different things, you look upon data and program as two sides of the
same thing: an object. The fundamental thinking behind object oriented
programming is that data isn't anything in itself but only something if
some piece of program operates on it. An object is therefore a collection
of data and methods (procedures and functions) to operate on those
data, collected in a way, similar to a record. Normally, you only from
the outside references the data in an object through the methods, not
directly. In this way you get incapsulation of your data: only inside the
methods code you need care about the details of the data used in the
object.

You declare an object like you declare a record, by using the reserved
word OBJECT instead of RECORD, and by writing procedure and
function headers inside the declaration.

Later on in your program, you write the content of the methods by


writing PROCEDURE object_type_name.procedure_name(...); or
FUCTION object_type_name.function_name(...):...; and then the block
belonging to this method. The method code then belongs to all objects
containing that method.

Objects can only be placed in xdata.

Example:

TYPE
Oo=OBJECT
X: Integer;
PROCEDURE DoX(Val: Integer);
140 PAS51
________________________________________________________

END;

...
PROCEDURE Oo.DoX(Val: Integer);
BEGIN
IF X<0 THEN
X:=X+Val;
END;

20.1 Inheritance.

One major feature on objects is that one object type may inherit the
properties from another object type and then add more data and / or
methods. The added methods may be a real addition (new name) or
may overwrite another inherited (same name). Data can only be added,
not overwritten.

Example; Inherits from example above:

TYPE
Oo1=OBJECT(Oo)
Y: Integer;
PROCEDURE DoXY(Val: Byte); (* really added *)
PROCEDURE DoX(Val: Integer);(* overwriting Oo.DoX *)
END;
...

PROCEDURE Oo1.DoX(Val: Integer);


BEGIN
IF X<=0 THEN
X:=X+Val;
END;

PROCEDURE Oo1.DoXY(Val: Byte);


PAS51 141
________________________________________________________

BEGIN
Y:=X+Y+Val;
END;

20.2 Virtual Methods.

In the overwriting in the last example Oo.DoX to Oo1.DoX, all objects


of type Oo will execute DoX as Oo.DoX and all objects of type Oo1 will
execute as Oo1.DoX. However, a very smart property of objects is to
make some methods VIRTUAL. In virtual methods, you do not decide
until runtime, which occurence of a method you want to execute, the
method declared in the object itself on a method in some object type,
from where the actual object type is inherited.

You make a method virtual by adding the reserved word VIRTUAL to


the method header in the object declaration. When a method has got the
predicate "virtual", all inherited methods with the same name must also
be "virtual".

The way virtual methods work is that it is legal to assign to an object


not only objects of the same type, but also of object types, from which
the current type is inherited. It then depends of the actual type of object,
assigned to the object, which method will be executed.

Example like above:

TYPE
Oo=OBJECT
X: Integer;
CONSTRUCTOR Init; (* see below why *)
PROCEDURE DoX(Val: Integer); VIRTUAL;
END;
Oo2=OBJECT(Oo)
142 PAS51
________________________________________________________

Y: Integer;
CONSTRUCTOR Init; (* see below why *)
PROCEDURE DoX(Val: Integer); VIRTUAL;
END;
...

PROCEDURE Oo.DoX(Val: Integer);


BEGIN
X:=Val;
END;

PROCEDURE Oo2.DoX(Val: Integer);


BEGIN
X:=Val*2;
END;

VAR
O1: ^Oo;
O2: ^Oo2;

BEGIN
O1:=New(Oo,Init);
O2:=New(Oo2,Init);
...
O2^.DoX(7); (* Oo2.DoX, X <- 14 *)
O2:=O1;
O2^.DoX(7); (* Oo.DoX, X <- 7 *)

20.3 Constructors and the extension to New.

Before you use an object, you may want to initialize something about
that object; to do that, you could use a special procedure. However, if
your object contains virtual methods, it is absolutely necessary to do
PAS51 143
________________________________________________________

that, using a special method, a constructor. The reason why you must
initialize in a special way, objects containing virtual methods, is that a
virtual method contains a dynamic address field inside the object that
must contain a valid address of a method, otherwise the program will
show unpredictable behavour.

A constructor itself can't be virtual.

As you often want to make space for an object on the heap and then
initialize it, and perhaps want to initialize it to an object, from which
this is inherited, the built-in procedure/function New() has been ex-
tended with an alternative form:

object_pointer:=New(Object_type_pointer, Init_construct);

As it is possible to call an init-method from within another descendant


init-method, where you do not want to initialize the virtual methods,
the compiler must have a way of finding out, which type of init call is
invoked.

You must therefore in SYSTEM51 Pascal initialize an object with


virtual methods through a New statement.

N.B. This isn't fully compatible with other compilers.

20.4 Destructors.

When finalizing use of an object, you may want to do some close-down


work. To be compatible with other Pascal compilers and possible future
extensions to this system, use a method called a destructor instead of a
normal procedure for such a purpose.
144 PAS51
________________________________________________________

20.5 The SELF variable.

When inside the code for a method, you need to reference the data of
the corresponding object. No problem, you just write the name of the
field as in a with-statement.

A method belongs to an object type, whereas the referencing must be to


an instance of that type, so how is this done?

At runtime, the compiler always places a pointer to the actual object in


a special variable called SELF. Normally you do not need to access
SELF, but in special cases, it may be convenient for you. Please notice
that SELF is placed in an absolute placed variable (and pushed
appropriate when calling other methods), so you can't, like in similar
systems, use the address of self as a unique description of the dynamic
object itself.

As self is a 2 byte entity, it can only point to 64KByte; it is decided that


those 64KBtes are the XDATA area. This is why objects can only be
placed in the xdata memory.

20.6 Parameters to Methods.

If you make your procedures and functions recursive by setting the


directive {$R+}, there are no problems with methods and parameters.
However, you will easily get big and slow code, so normally, you will
want to use the {$R-} (default) way of compiling.

This results in some extensions of the non-recursivity of the object


methods and some restrictions in their use:
PAS51 145
________________________________________________________

A non-recursive method uses the same absolute (x)data area for


parameters and local variables for all its occurrences, inherited or
not.

Inherited methods must therefore also have the same parameters as its
parent method.

20.7 Examples on Objects.

You may now think: is all this really something that I can use in my
embedded system, or is this only an academic possibility, not useful for
me and not practical with such a small processor? The answer is that
objects present a different way of thinking that offers you some
advantages and sometimes some disadvantages. The principles are
absolutely, as the below example should show you, useful also in the
type of jobs that these processors are normally used for. Some of the
advantages are that you get encapsulation and that you get a whole new
set of possibilities when using inheritance and virtual methods. Some of
the disadvantages are, that you tend to use more bytes for your program,
and that program execution isn't completely Read-Only when using
virtual methods, and therefore more sensible to errors.

Example:

In the following example, a microcontroller as a part of its purposes,


controls some valves; different valves using different interfacing
methods are or may be connected to the controller. The valve needs to
be set to some position, "Open" or "Closed", and we are interested in its
actual position. We could look at this as different procedures that could
do those operations each on a specific valve, but let us look at the valves
as objects, all alike. The first object type, TValve, considers a valve as
an abstraction, just "a valve". The details about this valve type is left
146 PAS51
________________________________________________________

unsolved, but it contains the valve position and methods to set and
retrieve the position. In this fundamental object, "SETVALVE" and
"GETVALVE" just writes to and reads from "Position". TValve.Init not
only executes the visible code that sets the position to "Open", but it
also invisibly initializes the addresses of the VIRTUAL methods of the
object.

{$M 0,$7FFF $8000,$FFFF} { When using objects, you must declare


some xdata memory }
TYPE
TValvePosition=(Open,Closed);

PValve=^TValve;
TValve=OBJECT
Position: TValvePosition;
CONSTRUCTOR Init;
PROCEDURE SetValve(V: TValvePosition); VIRTUAL;
FUNCTION GetValve: TValvePosition; VIRTUAL;
END;

PPortValve=^TPortValve;
TPortValve=OBJECT(TValve)
Mask: Byte; (* Port bit for actual valve *)
CONSTRUCTOR InitP(No: Byte);
PROCEDURE SetValve(V: TValvePosition); VIRTUAL;
FUNCTION GetValve: TValvePosition; VIRTUAL;
END;

PSerialValve=^TSerialValve;
TSerialValve=OBJECT(TPortValve)
Number: Byte; (* Valve number *)
CONSTRUCTOR InitS(No: Byte; BaudRate:Word);
PROCEDURE SetValve(V: TValvePosition); VIRTUAL;
FUNCTION GetValve: TValvePosition; VIRTUAL;
END;

CONSTRUCTOR TValve.Init;
PAS51 147
________________________________________________________

BEGIN
Position:=Open;
END;

PROCEDURE TValve.SetValve(V: TValvePosition);


BEGIN
Position:=V;
END;

FUNCTION TValve.GetValve: TValvePosition;


BEGIN
GetValve:=Position;
END;

We now turn to the implementation of some real valves. One type of


that is a collection of valves, all connected to a parallel port, each to
one bit of the port. The type TPortValve inherits the field Position as
this may be common to all valves. It also inherits the functionality of
TValve.Init, but as this object needs more initialization, TValve.Init is
called from within TPortValve.InitP.

CONSTRUCTOR TPortValve.InitP(No: Byte);


BEGIN
TValve.Init; (* Position set to open *)
Mask:=1 SHL No; (* Remember the valve port bit mask *)
P1:=P1 OR Mask; (* Actually set to open *)
Wait; (* Wait until physically moved *)
END;

PROCEDURE TPortValve.SetValve(V: TValvePosition);


BEGIN
IF V=Open then
P1:=P1 OR Mask
ELSE
P1:=P1 AND ($FF-Mask);
Wait;
Position:=V;
148 PAS51
________________________________________________________

END;

FUNCTION TPortValve.GetValve: TValvePosition;


BEGIN
(* Here comes code for getting a port valve position *)
GetValve:=Position;
END;

Now, one more different object inherits the properties of TValve:


TSerialValve, which corresponds with some valve through a serial
connection:

CONSTRUCTOR TSerialValve.InitS(No: Byte; Baudrate: Word);


BEGIN
TValve.Init;
Number:=No;
(* Here comes special initializations regarding the Baud rate *)
write(serial,Number,' INIT');
END;

PROCEDURE TSerialValve.SetValve(V: TValvePosition);


BEGIN
Position:=V;
write(serial,Number,' ',Position.X,' ',Position.Y);
END;

FUNCTION TSerialValve.GetValve: TValvePosition;


BEGIN
Write(serial,Number,' SENDPOSITION');
Readln(serial,Position.X,Position.Y);
GetValve:=Position;
END;
PAS51 149
________________________________________________________

Now we are ready to use the valves, and the dynamic properties of the
virtual methods:

VAR
Valves: ARRAY[0..2] OF PValve; { 3 different valves }
I: Byte;

...

BEGIN
Valves[0]:=New(PPortValve, InitP(0)); { #0 is parallel }
Valves[1]:=New(PSerialValve, InitS(1,9600); { #1 is serial }
Valves[2]:=New(PPortValve, InitP(2)); { #2 is parallel }

...

Now, we will take advantage of the virtual properties of SetValve:

FOR I:=0 TO 2 DO
Valves[I]^.SetValve(Closed);

If we hadn't declared SetValve virtual, only TValve.SetValve had been


called, because Valves[] is declared PValve, but because of the
properties ov virtual methods, TPortValve.SetValve (valve 0 and 2) and
TSerialValve.SetValve (valve #1) will be called instead, due to different
New - calls.
150 PAS51
________________________________________________________

21. Provisions for Concurrency.

Microcontrollers in embedded systems are often used in some real time


application. The microcontroller has to do the data acquisition and
control when the outer world needs it. If several processes are going on
in that world, the program in the microcontroller should be able to
service that at the proper time. A lot can be done in that way by using
the interrupt routines as shown in chapter 16.8. In some of those
applications however, this is impossible or very difficult to program.
For such applications PAS51 offers some low level primitives like in
the language Modula II, and an include file for medium level use of
those primitives.

21.1 Newprocess and Transfer.

The primitives and their implementations are designed especially for


optimal use of the microcontroller without external data memory, but
may of cause work with such memory too. They use a non-preemptive
scheduler strategy.

The type PROCESS is a built-in record, the fields not accessible from
PAS51 directly. It is intended to contain a runtime description of a
parameterless procedure turned into a parallel process by a call to the
procedure NEWPROCESS.

A call to the built-in procedure NEWPROCESS(pn,pd), where pn is a


procedure name and pd is a variable of type process, will place some
information about the starting point of pn and stack pointer of the 8051
in pd. This information will be used at later calls to TRANSFER.

A call to TRANSFER(pd1,pd2), where pd1 and pd2 are variables of


type process, will transfer the program execution from the pd1
procedure to the pd2 procedure.
PAS51 151
________________________________________________________

Some rules must be followed when using process, newprocess and


transfer.

1) Transfer must not be called inside an interrupt


procedure, i.e. using these build-ins is non-
preemptive.

2) The pn used procedure must be parameterless.

3) A transfer must never be placed in a function.

4) Be sure to have big enough PROCESS type


records to hold the full stack of each process. By
default, a PROCESS record must be placed in the
"data" memory, and only allow for a stack of 4
bytes; in this case, you should only call
TRANSFER from the very procedure that you
have made a process through NEWPROCESS. If
you want more stack space, use the directive {$P
n}, where n will be the maximum stack space -2.
In this latter case, PROCESS variables must be
placed only in "xdata" memory, and process
switching will therefore be slower.

5) Remember that procedures in SYSTEM51 Pascal


are by default non-recursive and therefore non-
reentrant. If you set the directive $R+, make sure
that you modify the ?TRANSFER in
PL51(7).ASM to also switch the ?FRAMEPTR
and ?FRAMETOP WORD variables.
152 PAS51
________________________________________________________

Example.

Program Round_Robin;
{ This program will demonstrate Round Robin Scheduling. }
{ At start-up only one process is active. }
{ After 16 repeats process1 will activate process2. }
{ After that, both processes are active and will alternate.}

type
procs=0..1;
var
sched_bits: set of procs;
sched,startp: process;
pd: array[0..1] of process;
cp,i: byte;

procedure scheduler;
begin
cp:=0;
repeat
if cp in sched_bits then transfer(sched,pd[cp]);
cp:=(cp+1) mod 2
until false
end;

procedure proc1; (* parallel process number 1 *)


begin
repeat
i:=i+1;
writeln('Process 1');
transfer(pd[0],sched);
if i=0 then sched_bits:=sched_bits+[1]; (* activate process 2 *)
until false
end;
PAS51 153
________________________________________________________

procedure proc2; (* parallel process number 2 *)


begin
repeat
transfer(pd[1],sched);
writeln('Process 2');
until false
end;

begin
newprocess(scheduler,sched);
newprocess(proc1,pd[0]);
newprocess(proc2,pd[1]);
sched_bits:=[0]; (* only process 1 active at start *)
i:=$F0;
transfer(startp,sched)
end.
154 PAS51
________________________________________________________

21.2 Signal and Waits.

The low level primitives NEWPROCESS and TRANSFER are as


earlier explained chosen because of the very limited internal data
memory space in a system without external data memory.
If however you are willing to pay the memory space cost or have
external data memory in your system, it is possible to use the primitives
to construct higher level parallel programming tool modules. Some
methods known from other systems are Concurrent Pascal Monitors,
ADA Rendez Vous and different sorts of semaphore mechanisms.

The module SEMAPHOR, included on diskette 2 of the version 3.0


implements a limited version of the semaphore mechanism, known as
signal semaphores. You may think of a signal semaphore as a special
sort of a counter variable, accessible through kernel procedures only. If
that counter is counted below some threshhold level, processes trying to
decrement the semaphore, will be delayed until some other process try
to increment that semaphore. Because the system is based on the earlier
mentioned primitives NEWPROCESS and TRANSFER, no timer- or
interrupt forced preemption scheduling takes place.
The system consists of up to 8 parallel processes, programmed as never
finishing procedures and made processes by call to NEWPROCESS for
each of the processes and made active by a general call to
STARTPROCESSES.

Those processes may be in 1 out of 3 possible states.


1) Running: the process whose code is actually executing on the CPU.
2) Active: the process(es) who could have been be running, but isn't
because another process is actually running. Processes may transfer
from state Running to Active by call to RELEASE_PROCESSES,
SIGNAL or in some cases WAITS. Processes will transfer from state
Active to Running in a round robin fashion when no Running process
exist.
PAS51 155
________________________________________________________

3) Suspended: the process(es) that waits for some event to happen. The
events may be detected by either another process or an interrupt routine.
Processes will transfer from state Running to state Suspended by a call
to WAITS if the semaphore S, parameter to WAITS, has reached the
low threashhold mentioned above. Processes will transfer from the state
Suspended to Active when some other process calls SIGNAL or an
interrupt routine calls ISIGNAL on S, and the actual process is the
longest waiting on S.

The module SEMAPHOR.OBJ with source code in SEMAPHOR.PAS


should be linked to a program using this mechanism. It defines 5
PUBLIC procedures, which should be declared IMPORTED in your
program or are predeclared in the file SEMAPHOR.ICL:

procedure SIGNAL(var signal_s: semaphore);


This procedure may be called from a process and will increment the
semaphore signal_s if signal_s>=8, else activate the longest waiting
process. Finally it transfers the process itself to the state Active.

procedure ISIGNAL(var isignal_s: semaphore);


Like SIGNAL, but called from an interrupt routine; no final transfer
occurs.

procedure WAITS(var waits_s: semaphore);


This procedure is called from a process. If waits_s<=8 then the process
will be suspended else the semaphore will be decremented. In the latter
case the process will go to state Active.

procedure RELEASE_PROCESSES;
Transfers the running process to state Active.
This procedure should be called from a running process on strategic
points to allow scheduling.
156 PAS51
________________________________________________________

procedure STARTPROCESSES;
This procedure should be called from the main program as the last
before end. ; Starts the whole kernel; no return beond this call takes
place. Before the call to this procedure, calls to NEWPROCESS for
every process in the system must have taken place.
In the start of your program, you must define the numbers of processes,
MAXPROCESSES=...
If the number is different from 3, you must reedit and recompile the file
SEMAPHOR.PAS.

An example of the use of the semaphore kernel, see the file


SEMADEMO.PAS on system diskette 2.
PAS51 157
________________________________________________________

22. Separately compiled units.

The SYSTEM51 version 5.0 allows separate compilation and later


linking of modules (in this system named units).

A complete ready-to-run program consists of one main program pro-


grammed in PASCAL and zero or more other modules, programmed in
pascal (then called units), assembler or another language that generates
the appropriate .OBJ format.

A main module may start with the syntax construct

PROGRAM <prog_name>;

If omitted, the prog_name will be that of the file.

Other modules must start with the syntax construct

UNIT <module_name> [OVERLAY n];

Please use the same name for the unit and the pascal file, because else
the simulator and the DEBUG51 won't work properly. This is true both
for the main program and for other modules.

To make types, consts, variables, procedures and functions known to


other modules, those items should be declared in the INTERFACE part
of the unit. Only the procedure and function heads are given in that
part.

The bodies of the procedures / functions, and the types, consts and
variables local to the unit, should be given in the IMPLEMENTATION
part of the unit, which follows the interface part. In this way,
implementation details may be hidden to other users of the unit.
158 PAS51
________________________________________________________

For units or programs to use definitions or procedures / functions,


declared in a Pascal unit, the name of that unit should be given in the
USES part of the program / unit.

In the following is given an example of how UNIT, USES,


INTERFACE and IMPLEMENTATION works together.

UNIT TestU; (* Separately compiled unit TestU.PAS with the name


TestU. *)

INTERFACE

USES
U1, (* This unit itself uses *)
U1, (* the other units U1.PAS, *)
U3; (* U2.PAS and U3.PAS *)

TYPE
TA=ARRAY[0..3] OF Byte;

PROCEDURE ProcU;
(* ProcU can be imported in other modules *)

IMPLEMENTATION

PROCEDURE ProcU;
BEGIN
... (* code for ProcU *)
END;

BEGIN
... (* this code is executed before the main code *)
END.

PROGRAM UProg;
USES
PAS51 159
________________________________________________________

TestU;
VAR
AA: TA; (* known from TestU *)
BEGIN
...
ProcU; (* --- *)
...
END.

To refer to variables, procedures and functions, declared in a non-


Pascal module, use the attribute IMPORT. The syntax of that is the
following:

For variables or constants add IMPORT after the name and type, just
before ;

For Procedures / functions add IMPORT after the reserved word


PROCEDURE / FUNCTION.

Types can't be imported from other languages.

To use variables, constants or procedures/functions, declared in a


Pascal unit, in modules for other languages, you need to know the
following: variables, constants and procedures/functions, declared in
the INTERFACE part of a unit, are exported (made public) with the
names <unit-name>?<name>

Another method, where you get the name itself exported, and which
may be used also in a main Pascal program is the following: Use the
attribut EXPORT, in procedures/functions just after this word,
otherwise after the type.
160 PAS51
________________________________________________________

If you are using a Pascal main program and only Pascal units, and
compiles from inside the IDE, the system will link all necessary
modules for you, and will also in most cases do the necessary
recompilation of units, where the source has been changed after last
compilation. If, however, you are using 1) include files in your units, or
2) modules written in other languages (for instance assembler or C) or
3) you have a long chain of units using each other and changes units
deep into the chain, the automatic compilation facility of the Pascal
compiler will not always work, use the .KPR project file facility.

If you are using more modules you are encouraged to to use the MAKE
facility of the integrated system. Write a .KPR project file.

The project file should contain

1) In the first line not starting with a "-", the name of the main file with
extension .PAS followed by the names of all include files for that file.

2) In the next lines the names of the modules including the extension
.PAS followed by the names of all include files for appropriate module.

3) Intermixed you may place lines with linker switches.

Example of a .KPR file:

MYPROG.PAS INCLUDEF1.PAS
-X2000
MODULE1.PAS INCLUDEF.PAS INCLUDE2.INC
MODULE2.PAS
PAS51 161
________________________________________________________

When compiling units, no automatic linking is performed, but units,


found in the uses part are recompiled if the source is newer than the
compiled files.

When compiling or making a main program from within the IDE, the
system recompiles any changed uses units and then finally links the
appropriate files. If "make" was used, and before linking, the IDE
system looks for a .KPR file; if found, it further compiles/assembles any
extra file, found in there, and then links according to the .KPR file list.

If not using the IDE, you need to manually link the files.

The syntax is either

LINK51 <main> <mod_2> <mod_3> <mod_n> FP51 -H

or

LINK51 @<link-file>

The file FP51 is only necessary when using REALs and / or


LONGINTs.

The <link-file> must contain a list of all files to be linked, each file or
linker directive on a separate line.

23. Bank Switching when Code >64 K Bytes.

When you get to the processor limit of 64 KBytes code, you are not
completely lost. SYSTEM51 Pascal offers you a solution, where you
may have programs up to 256 KBytes.
162 PAS51
________________________________________________________

To do this, you need to have some hardware that supports this. That
hardware should provide bankswitching of some upper part of your
code memory between different banks. The easiest border between low,
common code memory and upper banked memory is 8000H, but any
other limit may do, provided that low common memory has space
enough to hold 1) the main program, and 2) all interrupt routines, and
3) all runtime library routines included.
The code overlaying mechanism is based on units. Some units, declared
"overlay", will share upper code addresses, but will be placed in
different banks.

Overlayed units must be declared in the following way:

UNIT <name> OVERLAY <n>;

<n> is the bank number, in where you want the code to be placed.

To get the system know your specific software, you must modify the
routine ?SWITCHBANK in runtime library PL51.ASM (PL517.ASM)
to fit your hardware. When ?SWITCHBANK is called, the ACC
contains the new bank number; you must set your hardware according
to this.

If you use the Dallas Semiconductor 80C390, this processor has two
different ways of handling code memory > 64K; in version 6.5, only the
banked method is possible; to activate that method in SYS51W, you
must reassemble the file PL51.ASM after adding an additional
condition:

SWITCH390 GSET 1

The simulator partly supports bank switching. Three different


switching principles are available:
PAS51 163
________________________________________________________

1) Port 1, use SWITCHPORT1 GSET 1 in PL51.ASM


2) 80C390, see above
3) XData addresses 0FFFEH and 0FFFFH, use SWITCHXDATA
GSET 1
164 PAS51
________________________________________________________

24. Compiler directives.

Compiler directives are given in special comments, where a $ is imme-


diately following the { or (* . A directive consists of a capital letter
followed by parameters.

This is a complete list of the available directives.

(*$A<any assembler text>*)


will copy the text <any ... unchanged to the assembler source
file. May for instance be used for putting an assembler
directive $NOLIST into the .ASM file.

(*$B- Boolean expression shortcut off (default). Boolean


expressions will be fully evaluated.
(*$B+ Boolean expression shortcut on. Evaluation of boolean
expressins will stop with conditional jumps as soon as
possible.

(*$C+ or (*$C-
Comment terminate when long. Default on. If this directive
is on, comments can't be longer than 255 characters. This is
done for your comfort. When off, comments may have any
lengths.

(*$DEF <conditional define> *)


Defines a special variable <conditional define> and set its
value TRUE. To be used together wit $IFDEF or $IFNDEF.

(*$D-*)
No debug information is generated in the .OBJ and therefore
the .A51 file.
PAS51 165
________________________________________________________

(*$D+*) or (*$DS*)
Debug information concerning symbol names and types, and
character positions of pascal statement boundaries in the
code is generated into the .OBJ file and therefore into the
.A51 file. (Default and used by the simulator and DEBUG51,
but not INTEL standard)

(*$DB*) As $D+, but line positions are output according to Intel


standard. May be used by some 3. party emulators; ask them
if available.

(*$DEBUG51*)
Will generate debug information for KSC Software Systems
DEBUG51, version 5.0 or later by combining $D+ and $UI
directives. Can not be used for version 4.

(*$DL*)
Debug information concerning symbol names and line
numbers is generated into the .OBJ file and therefore into the
.A51 file. (INTEL standard and demanded by some
emulators, but not unambiguous)

(*$ELSE*)
Conditional compilation. See $IFDEF or $IFNDEF.

(*$F+ or (*$F-
Full 16 bit evaluation. In SYSTEM51 default off. In SYS517
default on. If on, bytes will always be expanded to 16 bit
before arithmetic operations. If off, 8 bit arithmetic
operations will occur between bytes as explained in chapter
15. The latter will give you efficient code, but may lead to
mistakes.
166 PAS51
________________________________________________________

(*$I<Includefile> *)
means including of some other source text file in
the main source text. The include-file must have
the extension .pas, but that extension must not be
given in the directive. he scanner of the compiler
will return to the main source when end-of-file is
met in the include file. Include files must not
contain include files themselves. As the order of
declarations of types, variables and procedures is
insignificant in PAS51, include file is a good tool
for modularity.

NOTE!! Include files are not presently supported by the


SYSTEM51 editor error finder facility and the
simulator and emulator pascal window facility.
The $D+ or $DL directive will generate no debug
information inside include files.

(*$IFDEF <conditional define>*)


Conditional compilation. If the special variable <conditional
define> is set true either through a $DEF or through the
main system menu, the following Pas51 code until next
corresponding $ENDIF or $ELSE directive will be compiled,
otherwise it will not be compiled.

(*$IFNDEF <conditional define>*)


Conditional compilation. If the special variable <conditional
define> is set true either through a $DEF or through the
main system menu, the following Pas51 code until next
corresponding $ENDIF or $ELSE directive will not be
compiled, otherwise it will be compiled.

(*$ISn*)
Controls the amount of PUSHing/POPping at interrupt entry
/ exit. Be careful when using this directive. Only use it when
interrupt speed is essential and you are sure that your
PAS51 167
________________________________________________________

interrupt routine or any called routine do not need the


PUSH/POP. Possible values for n are:

4=Save all (default & safest)


3=Save PSW, (& swBank), ACC, B
2=Save PSW, (& swBank), ACC
1=Save PSW (& swBank)
0=Save nothing

(*$JA*) will force 11 bit absolute jumps and ACALLs to be generated


instead of 16 bits. Default in Philips 87C751 and 87V752
processors, but may be used in small programs (<2KByte) for
other processors to save code space.

(*$JS*) Will force (+/-127) bytes short forward jumps to be generated


to save code; if the distance is too far, an error message will
occur, then use locally (*$JL*)

(*$JL*) (default) will force 16 bit longjumps or 11 bit absolute jumps


to be generated at forward jumps to ensure that any code
distance will compile in one pass.
168 PAS51
________________________________________________________

(*$L <main> <mod_2> <mod_3> ... <mod_n> *)


tells the SYSTEM51 main menu to automatic call the
LINK51 linker after a compilation, invoked from the system
menu. The directive may be placed in a main program
module if it contains any IMPORT or EXPORT declaration.
It is not necessary to express the pascal libraries FP51,
PASLIB51 or IODRIVER, as they are automatically added to
the list.
This directive will overload the MAKE facility through
Pascal Unit Uses and .KPR files of the system.

(*$LIBRARY
Generate a library source .ASM file. Must be placed before
any statements generating any code, including PROGRAM
or MODULE. For generating library files, please see
Appendix E.

(*$M <code-start>[,<c-end>] <xdata-start>[,<x-end>] *)


means that you may specify the start and end of
your memories. If your system does not contain
external memory, set <xdata-start> to -1 (default).
The (*$M directive has only its full meaning in a
main module. In all other pascal units, all code
and xdata RAM generation is relocatable, and
therefore the only meaningful $M directive will be
(*$M 0 0*) that defines the target having xdata
ram.
NOTE!! this directive MUST be placed before anything else
in your source text.

(*$O <internal ram address>*)


means that you may specify the (re)placement of
the following variables in internal ram memory.
May be used to optimize the usage of the limited
internal data memory. For further information see
next chapter.
PAS51 169
________________________________________________________

(*$O <procedure name>*)


means that you may specify the overlapping of
internal ram variables from different procedures or
functions. The following declarations of variables
in internal ram memory will be placed from the
same ram address as variables declared in <proce-
dure name>. May be used to optimize the usage of
the limited internal data memory. For further
information see next chapter.

(*$OC <code address> *)


(*$OX <external ram address> *)
Those directives acts like the assembler directive ORG. The
following code or external ram addresses will be placed from
the addresses given.

(*$PD*) Parameters will be placed in the data memory, offsetted to an


exported variable, called ?fkt?BYTE (default when using
data memory)

(*$PX*) Parameters will be placed in the xdata memory, offsetted to


an exported variable, called ?fkt?BYTE (default when using
xdata memory)

(*$P<size>*)
Parallel process descriptors will be placed in the xdata
memory by TRANSFER and NEWPROCESS. <size> is your
maximal allowable stack plus 2 for your processes.

(*$R-*) (default) A switch, which disables recursivity, i.e., places all


local variables and parameters on absolute addresses. Default
because it gives the most efficient code.

(*$R+ [n]*)
170 PAS51
________________________________________________________

A switch, which makes your procedures/functions recursive.


You must have declared xdata use in your system through a
{$M -directive before this directive. Parameters and local
variables will be placed in xdata, relative to ?FRAMEPTR.
The optional number n tells the system, how much xdata
memory (in 256 bytes pages) that you reserve for this xdata
stack. Default is 1 KByte.

(*$S n *) where n is a number 0 or 1.


Sets the symbol name generation type. if zero, the pascal
names will be used in the .ASM file and as debug
information. If one, synthetic names ?S0, ?S1, ... , will be
used for local variables in the .ASM file and as debug
information. This is made an option to overcome the problem
that pascal uses scope rules for variable names, whereas
assembler uses a "flat" rule, and the problem that the
assembler uses the names A, B, C and DPTR for special
purposes. (Default 0)

(*$T+*)
means that Pascal-like extensive type checking is
performed throughout the compiling process
(default).

(*$T-*)
means that weaker type checking is performed:
Pointers are treated like WORDs, i.e. may be
added, subtracted or the like.

(*$U+*)
means that the compiler will generate a LJMP
instruction on every statement border in the
program. This may be used for debugging
necessary in certain debugging systems.

(*$UI <byte1> <byte2> <byte3> *)


PAS51 171
________________________________________________________

means that the compiler will generate those 3


bytes of instructions on every statement border in
the program. This may be used for general
debugging purposes. For the DEBUG51 the bytes
must be $12 0 $33 (CALL $33)

(*$U-*)
means no extra instructions generated. (default)

(*$UNDEF <conditional compile> *)


Conditional compilation. Sets the <conditional compile>
special variable to false. See $IFDEF or $IFNDEF.

(*USING n*)
Sets the default register bank, used by all subsequent non-
interrupt functions/procedures to n.

25. Optimization of Internal RAM Space.

If you have got only data memory in internal ram, it is some of an art to
get enough space for variables and stack. If you get into trouble, the
following might be done:

1) If you use 8051, 8751 or 8031, you might shift to


8052, 8752 or 8032. Will give you 128 bytes.

2) If you use REAL, LONGINT or string con-


catenation, you may consider, if this is necessary
for you. If not, this will give you 21 bytes.
172 PAS51
________________________________________________________

3) Then SYSTEM51 is, as explained in chapter


16.5.2, by default ( $R- state) not using recursivity.
Normally all variables in main program,
procedures and functions are consecutively placed
in memory. To optimize this, you may use the
(*$O compiler directive.

25.1 Using the (*$O Directive.

The (*$O proc1 directive is used to optimize the usage of internal RAM
space. If You as programmer know that certain procedure(s) or
function(s) proc2 will never call some other procedure(s) or function(s)
proc1, you may force the compiler to place the parameters and local
variables at the same RAM space by placing the directive (*$O proc1
just before the declaration of proc2. Indeed this compiler directive will
force variable allocation to proceed from the same address as proc1.

With the (*$O <address> directive, you may force internal ram
allocation to take place from the absolute address <address> no matter
what the compiler else has placed there. If you know the address, this
may be used as before, or you may use it to separately compile more
modules in the same or different languages.
PAS51 173
________________________________________________________

26. Runtime Error Handling.

Most microcontrollers are used in imbedded systems. therefore,


normally, there will be nowhere to signal runtime errors. This implies
that there is no runtime checks automatically performed in the
generated code. If you want to check for array index ranges, stack
overflow, variables out of range, divide by 0 etc., you must supply your
own code for that.

27. Compile Time Error Handling.

27.1 Errors.

During compile time, an extensive error checking is performed. A list


of possible error types is given in Appendix B. As the compiler is
exclusively used in SYSTEM51, you will be given at any detected error
the choice to go directly into the build-in editor with the cursor placed
at the erroneous text point and the error text in the status line of the
editor. You are encouraged to do this as error recovery is weak in the
compiler.

27.2 Stack Overflow Warning.

The PAS51 compiler will try to calculate the maximal size of your stack
use. The stack in the 8051 is placed in the internal RAM. It is therefore
rather small. If you get a warning of possible stack overflow, don't give
up, but inspect your .asm and .pas file carefully. It is likely that you will
never exceed the stack size limit, but that the compiler just don't know
how you have intended to run your program.
174 PAS51
________________________________________________________

28. Information on memory and register use and


parameter passing.

28.1 Register Use.

Bank 0 is used for non-interrupt and slow-interrupt purposes, bank 1, 2


or 3 in fast interrupt routines. Registers 0 to 1 are used for accessing
indirectly accessible DATA or IDATA items. Registers 2 to 7 are used
for scratch pad use in expression evaluation. Especially are register 2
and 3 used as a 16 bit accumulator and 4 and 5 as a 16 bit B register in
word or integer calculations.

Before calculation of parameters for a new function call, old relevant


data in registers are pushed on the stack.

28.2 Parameter Passing.

Parameters in procedures and functions are, in the default non-


recursive model, treated as local variables known to the calling
program part at procedure call time. Actual parameters are placed
directly into the memory position of the formal parameters. Function
return values are treated in just the same way: when returned from a
function, the function value are moved from the function return value
position in memory to the expression evaluation position.

To be able to decide, whether parameters will be placed in data memory


(default) or xdata memory, two compiler directives exist, {$PD},
PAS51 175
________________________________________________________

{$PX}; notice that mixed parameters in bit, data and xdata memory is
no longer possible like it was in earlier versions of the compiler.

When recursion is on ( {$R+} ), parameters are passed in xdata


memory, relative to a build-in variable called ?FRAMEPTR (seen from
the called procedure) or ?FRAMETOP (seen from the calling one).

28.3 Memory organization.

28.3.1 Internal Data Memory.

Addresses 0 to 31 are used for register banks as explained in 28.1.

The bits at (byte) address 32 are used for scratch-pad purposes by the
DEBUG51.

All other addresses are relocatably managed at link time. The only
space that the runtime packages will demand is 1 PUBLIC byte called
?STACKPTR containing the initial value of the stack pointer, in case of
external RAM present 1 PUBLIC integer called ?HEAPPTR,
containing the address of the first free address on the heap.

If you use LONGINT or REAL type variables, a special DATA area


called ?FLOATBUFFER, 16 bytes in size will be reserved. This area
will also be used for string addition if you don't have declared any
XDATA memory in your configuration.

Floating point transcendental functions like COS or EXP uses extra 31


bytes. If you havn't declared any external memory ( no $M directive),
they will be of type DATA, otherwise they will be of type XDATA.
176 PAS51
________________________________________________________

The stack will be placed in the first free DATA area, in case of a
processor type with high internal ram in the first free IDATA area.

If you use a target with high onchip data ram, no external data ram and
no separate modules (no public or import), then the compiler will
automatically shift variable address allocation from DATA to IDATA
when DATA is supposed to be full. In all other cases you must
explicitly declare variables IDATA, if you want them placed in high
onchip RAM.
PAS51 177
________________________________________________________

28.3.2 External Data Memory.

The presence of an external data memory must be declared with the


{$M directive. If present, the lowest part will be used for (external
declared) variables, the part above for the heap. It will always be
accessed in the large model of the 8051, i.e., all 16 bit of address will
be output to port 1 and 3.

If T)arget option 8031, 8032, 80532 or 80535 is selected, it will not be


possible to address port 0 and 2 from a program.

28.3.3 Program Memory.

The compiler always generates PROMable code. It may be placed in


internal or external program memory.

Although the separated program and data memory model is supposed


by the compiler, you may use combined memory by proper use of the
{$M directive.

29. Interfacing Pascal with assembler or SYS51C

This chapter describes first the facts about how the Pascal version 5
parameter transfer works, and then gives you a cookbook of how to
implement it in practice. Please note that the version 5 way of para-
meter transfer is different from that of earlier version.

If you havn't set the compiler directive {$M cccc xxxx} where xxxx<>-
1, your default memory is "data", the chip internal 128 bytes data area.
Parameters will be placed in "data", with an offset >=0 to a position
178 PAS51
________________________________________________________

called ?fkt?BYTE, where fkt is the name of the procedure/function. If


you for instance have two parameters Param1: LongInt and Param2:
Byte to a procedure Proc, Param1 will be placed at ?PROC?BYTE, and
Param2 at ?PROC?BYTE+4, because a LongInt variable is 4 bytes
long.

If you have set the compiler directive {$M cccc xxxx} to xxxx>=0, but
havn't set the {$R+ directive, parameters will be placed absolute in the
"xdata" memory with the same notation as in "data" memory, i.e.
relative to ?fkt?BYTE.

With the directives {$PD} and {$PX}, you might switch the parameter
memory. This may be necessary, if you want to interface to some third
party products.

If you set the compiler directive {$R+}, both parameters and local
variables are placed relative to a certain frame in xdata.

The address of the 1. parameter when entering an assembler routine


from pascal in this mode, is placed in a (data placed, 2 bytes wide)
variable called ?FRAMETOP. The next parameters follow.

The last part of this chapter is intended rather as a cookbook for


interfacing SYS51C and assembler than a systematic list of how
PASCAL51 parameters and return values are represented.

When you need to write something in assembler to be called from


Pascal or the opposite, we propose you to do the following steps:

1) Write a skeletton Pascal program that uses the same value,


var parameters and return values in its procedures and
functions as the assembler module you want to write.

2) Compile that module with the .ASM generation switch on.


(In the integrated environment this is Alt-T/G/Y)
PAS51 179
________________________________________________________

3) Rename the generated .ASM file, so that you do not by


mistake recompile the Pascal file later on and therefore
destroy your effords in 4).

4) Edit that .ASM file, knowing that the compiler do not expect
any registers, not used for interfacing the function, to be
saved by you.

5) Assemble that module.


180 PAS51
________________________________________________________

Appendix A. Predefined Variables, Constants and Types.

Following simple types are predeclared:

BYTE, WORD, INTEGER, LONGINT, REAL, CHAR, BOOLEAN,


PROCESS.

Following constants are predeclared:

NIL, FALSE, TRUE.

Following (byte) variables are predeclared for target 8051:

P0, P1, P2, P3, IP, PSW, B, IE, TMOD, TCON, TH0, TL0, TH1, TL1,
SCON, SBUF, PCON.

Following (boolean) variables are predeclared for target 8051:

IT0, IE0, IT1, IE1, TR0, TF0, TR1, TF1, RI, TI, RB8, TB8, REN,
SM2, SM1, SM0, EX0, ET0, EX1, ET1, FS, EA, PX0, PT0, RX1, PT1,
PS, P, OV, RS0, RS1, F0, AC, CY, INT0, INT1, T0, T1.

For other targets, please refer to the relevant files xxxx.SFR.


PAS51 181
________________________________________________________

Appendix B. Error messages.

B.1 Error messages from the PAS51 compiler.

1 No source file present


4 Unterminated program
5 Disk is full
6 Comment longer than 256 characters,to allow long comments, use
{$C-}
7 Includefile not present
8 Not enough memory in your PC
9 Label not declared
10 Constant definition must be integer or char
11 Subrange definition must be integer or name
12 Index definition must be subrange
13 Interrupt procedure can't call non interrupt procedure or vice versa
14 Parameter mismatch
15 Number of parameter mismatch
16 Ordinal can't be taken of this type
17 Type can't be FOR step variable
18 Missing to or downto
19 Case label must be simple constant
20 Only sets of up to 8 elements allowed in this implementation
21 No external memory declared in your installation
22 Pointers only permitted if external memory in your installation
23 No single record can exceed 255 bytes in total
24 Array index out of range
25 Only bank 1 to 3 may be used for fast interrupts
26 Var specified actual parameter must reside in same memory as
formal
27 Label must be declared integer
28 With nested too deep
29 Compiler construction error: code generation error in ext ram or
const array.
30 Bit selector>7
31 Byte constant>255
32 Byte can't be negated here
182 PAS51
________________________________________________________

34 No bit arrays or record fields allowed here


35 No assign of structured variables here
36 Floating point routines not reentrant.
39 Compiler construction error: Error in register allocation.
40 Codegeneration impossible here
41 Codegeneration impossible, too complex record or array structure
42 No codegeneration for assign possible here
44 Compiler construction error: evaluation stack underflow
45 Compiler insufficiency: expression too complex
46 Compiler limitation: runtime stack overflow
48 Compiler limitation: evaluation stack overflow
50 Dublicate EXPORTed name
51 Dublicate name
52 Undefined name
53 Name misused
54 Unknown character
55 Error in constant
59 Must be byte
61 Variable must be array or string
62 Subscript expression must be integer
63 Expression must be boolean
64 Operation not permittet on this type
65 Type incompatibility in this operation
66 Type incompatibility in this operation
67 No read operation on this type
68 No write operation on this type
69 Expression must be boolean
70 Variable preceeding ^ not declared pointer
71 Typecast not possible here
72 Variable preceeding . must be bit selectable special register or type
record
73 Wrong type for this file type
75 No boolean in XDATA or IDATA
76 Parameter error
77 Expression must be string
78 Set elemernt type mismatch
79 Only = or <> allowed on structured variables
PAS51 183
________________________________________________________

80 Compiler buffer full; use more procedures


81 Objects must have a type name
82 Not more than 256 EXTERNALs possible in one module
83 Compiler limitation: array of bit not allowed
85 Not enough internal memory
86 Pointer definition without external memory declared
90 Directive too long
92 Error in DOS command line
93 Constants arrays or strings on both sides of compare can't be
compiled
94 Distance too far when using {$JS}, use {$JL} instead here
95 In VAL(), string and variable must reside in same memory
96 Unknown directive
97 Variable or constant expected
98 Pointer must be identifier
99 Not implemented function on this special micro
100 Identifier expected
101 Integer constant expected
102 Character constant expected
103 String constant expected
107 '*' expected
111 Relational operator expected; for instance = in type definition
117 ')' expected
118 '(' expected
119 '(.' or '[' expected
120 '.)' or ']' expected
121 ',' expected
122 ';' expected
123 '.' expected
124 ':' expected
125 ':=' expected
126 '..' expected
131 'OF' expected
132 'BEGIN' expected
133 'END' expected
135 'THEN' expected
138 'DO' expected
184 PAS51
________________________________________________________

141 'TO' or 'DOWNTO' expected


148 'UNTIL' expected
163 '^' expected

B.2 Error messages from the ASM51 assembler.

I Include file error: file not found or nesting not


allowed.
M Multiple defined symbol; I you assemble sources
generated by the Pascal compiler, you may need to
know about the {$S directive.
O Too far for short jumps: distance exceeds +127/-
128 bytes.
P Phase error; address of label different between
pass 1 and pass 2; may be caused be caused by M
error.
Q Questionable line: The assembler doesn't
understand the line at all.
R Relocation impossible.
S Syntax error: The expression evaluator found an
error.
U Undefined symbol.
PAS51 185
________________________________________________________

B.3 Error messages from the LINK51 linker.

1 Improper .OBJ format: wrong module record


2 Improper .OBJ format: wrong record length
3 Improper .OBJ format: wrong module end record
4 Differences in module names between passes
5 ACALL or AJMP out of 4Kbyte block
6 Improper .OBJ format: Unknown record
information
7 Improper .OBJ format: Checksum error
8 Improper .OBJ format: Unknown record type
9 No main file name in command line
10 Bit addressable space exceeded
11 Improper .OBJ format: record too long
12 Dublicate module name
13 Dublicate PUBLIC name
14 Memory type mismatch between PUBLIC and
IMPORTED
15 Unresolved IMPORTED (EXTRN)
16 CODE memory overlap
17 More than 32 segments in one module
18 Not enough memory in your PC; if you use the
integrated environtment, use the stand only
version instead.
19 File not found
186 PAS51
________________________________________________________

Appendix C. How to Design Your Own Low Level Input/Output


Driver.

The procedures write and writeln call a routine WRITC in I/O part of
the runtime library when writing a character. This routine may select 5
different ways to output that character.

Using the output serial device of the 8051 is default in write and writeln
and is implemented in a polled way. The code already existing in the
library may be described, although not implemented so, in the
following PAS51 procedure:

procedure writc(ch: char);


begin
while not ti do;
ti:=false;
sbuf:=ch
end;

The serial channel and its baud rate generator is not automatically
initialized by the system. If the statement RESET or RESET(SERIAL)
is used before use of write(ln) or read(ln), then a standard setup is
executed, corresponding to the inclusion of the following pascal code:

TMOD:=$20 { timer1 mode 2 }


SM0:=false;
SM1:=true; { set uart mode 1 }
TH1:=250; { 9600 baud @11.0592 MHz }
TR1:=true; { enable timer1 }
PCON:=$80;
TI:=true;
REN:=true;

For other setups, you may either include a modified version of the code
in your program, or you may modify and reassemble the file
IODRIVER.ASM, LIBRARY RESET.
PAS51 187
________________________________________________________

In case of a 12 MHz clock CPU, the baud rate may be modified by


using:

300 Baud: TH1:=48


600 Baud: TH1:=152
1200 Baud: TH1:=204
2400 Baud: TH1:=230
4800 Baud: TH1:=243

In case of a 11.0592 MHz clock CPU, the baud rate may be modified by
using:

300 Baud: TH1:=64


600 Baud: TH1:=160
1200 Baud: TH1:=208
2400 Baud: TH1:=232
4800 Baud: TH1:=244
9600 Baud: TH1:=250
19200 Baud: TH1:=253

Please notice that if you use a 8052 or 80C515/517 like processor, there
are alternative timers to TIMER1; you must program that yourself.

Write(display,... will output through the routine WRITC to a LCD


display, for instance of the type SANYO LCM 522, connected to the
chip as explained in the file IODRIVER.ASM or in application note 1
from KSC Software Systems. NOTE!! This device must be initialised
by the programmer before use.

Write(soft,... will output through the routine WRITC to a software


serial UART to P3.5. This is compatible with the communication
system of KSC Software Systems In Circuit Debugger.

Write(user1,... or write(user2,... let you design your own WRITC output


drivers. You must modify and reassemble the file IODRIVER.ASM to
meet your needs.
188 PAS51
________________________________________________________

The procedures read and readln call a routine READC in I/O part of the
runtime library when reading a character. This routine may select 4
different ways to input that character.

Using the input serial device of the 8051 is default in read and readln
and is implemented in a polled way.

Read(soft,... will input through the routine READC from a software


serial UART using P3.2. This is compatible with the communication
system of KSC Software Systems In Circuit Debugger.

Read(user1,... or Readln(user2,... let you design your own READC


input drivers. You must modify and reassemble the file IO-
DRIVER.ASM to meet your needs.

Some general conventions exist: Device numbers will always be present


in R3 when calling one of the needed subroutines. Device numbers <8
denotes special devices, whereas values >=8 numbers general text files.
The PUBLIC declared subroutines ?WRITC, ?READC, ?FILEASSIGN,
?RESET, ?REWRITE, ?CLOSE, ?EOLN, ?EOF must be implemented.
For further details, see the file IODRIVER.ASM.
PAS51 189
________________________________________________________

Appendix D, floating point precision and limitations.

The representation of the type REAL is the following:

(msb) s (1 bit) e (8 bit) m (23 bit) (lsb)

totally 32 bits or 4 bytes.

The value v is determined by

if 0<e<255 then v=(-1)s*2(e-127)*(1.m).


if e=0 then v=0.
if e=255 then v is a NaN

NaN is the result of a division by zero.

During calculation inside one expression, the floating point package


uses a mantissa of 32 bit, no rounding, the accuracy of division is 29
bit, other operations 31 bit. When results of expression calculations are
stored in REAL variables, it is packed using rounding according to the
above mentioned format.

Floating point calculation uses 2 fixed address, 5 bytes registers, a


floating point ACC and a floating point B register. Furtherfore, two
fixed address bits are used by the package. This means that the floating
point package isn't reentrant, so you can't use reals in interrupt
routines. Even if you push those registers, you can't use interrupts as the
package uses bank 0 code.
190 PAS51
________________________________________________________

Two versions of the code for WRITE(LN) of REALs is delivered. In


package 1, represented by the original file FP51.OBJ, formatting is
possible; in package 2, represented by the file FP51S.OBJ, a standard
formatting is given.

In package 2, WRITE and WRITELN of reals uses a simple algoritm


and therefore doesn't occupy any extra RAM bytes at all and only a
minimum of code. This also means that no formatting WRITE(x:n:n) in
this case is possible and that the last (7.) digit might be questionable.

To activate package 2, copy the file FP51S.OBJ to your SYSTEM51


directory as FP51.OBJ.
PAS51 191
________________________________________________________

Appendix E, Generating Library .OBJ Files

By using the {$LIBRARY compiler directive, you may build your own
libraries out of Pascal modules using the following steps:

If you want to make your own library MYLIB.OBJ file out of the Pascal
sources p1, p2 and p3, please follow the steps:

1) In top of p1.pas, p2.pas and p3.pas place {$LIBRARY}

2) compile the 3 sources.

3) with the editor Alt-N MYLIB, Alt-Y/D, prepare a file MY-


LIB.ASM with the following code

NAME MYLIB

$INCLUDE P1.ASM
$INCLUDE P2.ASM
$INCLUDE P3.ASM

END

4) assemble this file pressing Alt-Y/A in the integrated environ-


ment.
192 PAS51
________________________________________________________

Appendix F, Hints for PLM51 Users.

The version 4 of the SYSTEM51 uses the same relocatable file format
as the INTEL PLM51. It is therefore in principle possible to link
PAS51.obj modules to PLM51.obj modules.

However, some precautions must be taken.

The runtime libraries (FP51.OBJ, PL51.OBJ and IODRIVER.OBJ for


PAS51 and PLM51.LIB for PLM51) are different and must all be
linked.

The data type WORD in PLM51 is stored msb first, whereas the data
types WORD or INTEGER in PAS51 is stored lsb first. To solve this
problem you may define and use the following function before
exporting or after importing to / from PLM51:

FUNCTION PLMWORD(W: INTEGER): INTEGER;


BEGIN
PLMWORD := W SHL 8 + HI(W);
END;

Parameters to a procedure PP in PLM51 are not exported and imported


by their real names, but by artificial ones ?PP?BYTE (plus offset). In
PAS51 as described earlier, parameters are exported and imported by
their reral names. This problem may be overcomed by defining a record
?PP?BYTE of a type, covering the pascal parameters. (Normally, '?' in
pascal names should be avoided although they for this purpose in fact
are permitted).

Parameters in PLM51 are always passed in internal ram memory


DATA, whereas parameters in PAS51 are passed in DATA when no
XDATA is declared (No $D directive given or second parameter -1)
and otherwise in XDATA, unless a specific DATA qualifier is given.
PAS51 193
________________________________________________________

Appendix G, Sample INTEL .HEX Loader.

(************************)
(* *)
(* H E X L O A D *)
(* *)
(************************)

(* KSC Software Systems 1991 *)

(* This sample program will load *)


(* an INTEL .HEX file into a 8051 *)
(* memory; to execute the program,*)
(* XDATA and CODE must be over- *)
(* lapping. *)

{$M 0 -1}
{ Must be changed to serve your hardware
}
program hexload;
var
adr: word;

procedure loadhex;
var
ch: char;
cs,count,number: byte;
procedure getch;
(* returns next character in ch *)
begin
read(ch);
end;
function hex: byte;
(* returns next hex pair of hex digits
*)
194 PAS51
________________________________________________________

var
bb: byte;
function nibble: byte;
begin
getch;
if ch>'9' then nibble:=ord(ch)-55
else nibble:=ord(ch)-48;
end;
begin (* hex *)
b:=nibble shl 4 + nibble;
cs:=cs+bb;
hex:=bb;
end;
begin (* loadhex *)
getch;
repeat
while (ch<>':') and (ch<>#27) do
getch;
(* ESC used as end_of_file mark *)
if ch=':' then
begin (* block to read *)
cs:=0;
number:=hex;
adr:=word(hex) shl 8 + hex;
count:=hex; (* dummy read hex *)
if number>0 then
begin
for count:=1 to number do
begin
xmem[adr]:=hex;
inc(adr);
end;
count:=hex; (* dummy read again *)
end;
end;
PAS51 195
________________________________________________________

until (number=0) or (ch=#27);


end;

begin (* MAIN PROGRAM *)


reset(serial);
writeln('Download program now:');
hexload;
adr:=$8000;
(* depends on your hardware *)
writeln('Starting program at',
adr);
exec(adr);
end.
196 PAS51
________________________________________________________

Index
CMEM
Build-in array, 99
—2— Code
256 KBytes 256 KBytes, 166
Code, 166 CODE statement, 114
Code.
Embedded, 114
—A— Code-start, 172
Abs CodeWindow
ABSOLUTE,, 99 Simulator, 43
Active Comment, 93
Semaphores, 158 Compiler Directives, 93; 168
ADDR, 126 Concurrency, 142; 153
ARCTAN, 129 Constants, 100
ARRAY, 95 Constructor
ASCII, 94 COS, 129
Assembler, 74
Interfacing to, 181 —D—
Assembler Directives, 74
Assignment, 101 DATA, 98
AT DataWindow
Compiler absolute placement, Simulator, 43
99 Dec
Delete a character, 29
Destructor
—B— Device name, 104
Bank switching Directives
Overlay, 166 Assembler, 74
Beautify, 28 Compiler, 93; 168
BOOLEAN, 94 DISPLAY, 104
Breakpoints, 36
—E—
—C— Editor
C, 1; 91; 138; 140 Moving around, 26
Case Statement, 109 Embedded code, 114
CHAR, 94 Emulators, 73
Character constants, 92 Eof
CHR, 126 no, 103
PAS51 197
________________________________________________________

Eoln Inc
no, 103 Includefile, 170
Error Handling, 177 Inheritance.
Errors Object oriented programming,
SYS51C, 34 143
Examples Input, 102
Assembler, 80; 81; 84 Installation, 3
Exec INT, 127
Exit, 128 INTEGER, 94
EXP, 129 INTEL HEX
Expression, 101; 115 Linker generation, 86
External memory start, 172 INTERFACE
Units, 161
Interfacing
—F— to assembler or C, 181
For Statement, 111 INTERNAL, 98
Functions, 119; 123 Interrupt, 132

—G— —K—
GOTO, 115 keystrokes
editor, 26; 28
—H—
—L—
Hexadecimal
Pascal, 92 LENGTH, 126
HI, 126 Linker, 86
HighNib ListWindow
HllWindow Simulator, 43
Simulator, 43 LN, 129
LO, 127
LowNib
—I—
I/O, 106 —M—
ICE, 73
IDATA, 98 MARK, 138
If Statement, 108 Menues
IMPLEMENTATION Simulator, 38
Units, 161 Method
In Circuit Emulator, 73 Object oriented programming,
142
198 PAS51
________________________________________________________

Mnemonics Ports, 102


assembler, 74 Preemption, 158
Modula II, 153 Procedures, 119
Monitors, 158 PROCESS, 95; 154
Mouse, 13 Pseudoops
Moving around assembler, 74
editor, 26 Pulldown menues, 12
Simulator, 38
—N—
—R—
Named Constants, 100
Names, 92 Read, 103
NEW, 138 Readln, 103
Object oriented programming, REAL, 95
146 RECORD, 96
NEWPROCESS, 154 Recursivity, 124
NibToByte RegisterWindow
Nonvisible characters, 28 Simulator, 43
Numbers, 92 RELEASE, 138
Rendez Vous, 158
Repeat Statement, 110
—O— Repetition, 110
Object Round
Object oriented programming, Converting real, 127
142 Round Robin Scheduling, 156
Optimize Running
Internal RAM, 176 Semaphores, 158
ORD, 126 RunWindow
Output, 102 Simulator, 43
Overlay
Bank switching, 166 —S—
Scheduling, 158
—P— Semaphore, 158
Parameters, 120; 121 SERIAL, 104
Pascal, 1; 91 Serial buffer input/output
PL/M, 1; 91; 138; 140 Simulator, 37
Pointer Set, 140
Pointers, 138 SET type, 97
PORT_AND Signal, 158
PORT_OR Simulator, 36
PAS51 199
________________________________________________________

Commands, 37; 38; 57 USER, 104


SIN, 129 USES, 162
SOFT, 104 USING
Special function registers Compiler directive, 175
SFR Compiler, 87 Interrupt, 132
Special symbols, 92
SQR, 129
SQRT, 129
—V—
Str, 128 Val, 127
STRING, 97 Variables
Suspended Pascal, 98
Semaphores, 159 Virtual
SYS51C, 182 Object oriented programming,
144
—T—
Tabs, 29
—W—
TAN, 129 Waits, 158
Terminal, 102 WatchWindow
TRANSFER, 154 Simulator, 43
Trunc While Statement, 110
Tutorial, 7 WITH statement, 112
Type checking, 174
Type declaration, 95
Typecast, 131
—X—
Types XDATA, 98
Pascal, 94 XDataWindow
Simulator, 43
—U— XMEM
Build-in array, 99
UNIT, 161

You might also like