This programming guide is for Remote Processing
controllers using RPBASIC-52 language. It was
derived from Intel MCS-51 BASIC, V1.1. Several
command extensions and features have been added
to effectively speed up command execution.
MBuffered serial ports. Received characters are
buffered to 256 characters. PRIN T strings are
put into a 256 character buffer, making it much
faster.
MMulti-tasking constructs such as ON LINE, ON
COM, ON COUNT, and ON KEYPAD. Lines
and keypad are monitored at assembly language
speed on every 5 ms tick time. This speeds up
program execution because the main program
no longer has to monitor these points.
MSoftw are co mm ands d irectly support hardw are.
DATE and TIM E work with the rea l time clock .
AIN reads a voltage while AOT outputs one.
Some cards do not have all hardware features so do
not support all of the commands. Cards supported or
exceptions are listed with each command. In some
cases you must refer to your hardware manual for
exact ranges.
A few original BASIC-52 commands have been
removed. These commands were oriented around
specific registers in the 8052 chip or a specific
design. For example, the PROG command assumed
code is stored in an EPROM. Remote Processing
cards use a flash EPROM which uses a new
programming algorithm. The PROG command was
replaced with SAVE.
MANUAL CONVENTIONS
Information appearing on your screen is shown in a
different type.
<xxx> Paired angle brackets are used to indicate a
specific key on your keyboard. For
example, <esc> means the escape key.
exprTerm m eaning a num ber, simple
variable, or mathematical expression
involving variables and numbers. The
following are valid expr:
45.3
B
CYCLE
B*45
C*D+54
INT( D)
expr can be another function.
Complexity of expr is limited by
available stack memory. Usually this is
7 levels of parentheses.
For clarity, expr may be another name
such as position, channel, and so on.
italicItalicized variables require an
expression or value. For example:
AIN(channel)
KEYPAD(function )
Ellipsis (...) follow an instruction w hich optionally
accept more data.
DATA data[,data][,data]...
READ variable[,variable]...
Optional portions of an instruction are enclosed in
brackets []:
DISPLAY option[,option][,option]
1-1
Page 5
RPBASIC-52 PROGRAMMING GUIDE
Basic Interpreters
There are several ty pes an d leve ls of inte rpreter s. A
slow, very basic type of interpreter figures out what
each command is sup posed to do du ring run time . A
token-based interpreter, such as this basic, is much
faster. This type examines each program line as it is
typed in, figures out what it should do, and converts
it to a string of B asic to kens m ixed w ith text . A
token is a single character that represents a
command. For example, an ASCII value of 89H
represents the PRINT com man d.
After a line is p rocess ed, it is st ored in mem ory.
When you type the RUN command, each program
line is scanned. A token causes a branch to an
assembly language routine which carries out the
required action.
ELEMENTS OF A BASIC PROGRAM
Commands
Com man ds dire ct or pe rform an out put ac tion.
Exam ples ar e PR INT , SAV E, POKE, and LOAD .
Commands do not return a value used for
computation.
Functions
Tasking statements define a condition and execution
location when a condition is m et. Statemen ts
include ON COM $, ON LINE, ON COUN T, and
ONITR. Programs executed as a result of these
statements are treated as subroutines. The only
difference between a tasking routine and one called
by a GOSUB is the tasking can be called at any
time.
Expressions
An expression is a combination of instructions,
operators, data (constants, arrays or strings) and
variables which, when evaluated by B asic, is
equivalent to a single numerical value. Many Basic
comm ands accep t expressions as w ell as explicit
data. Expressions which are used by commands and
functions are also called arguments.
WRITING AND EDITING PROGRAMS
Program development takes place on your PC using
your word processor or the RPC card. Programs
from your PC are downloaded using a serial
communication program.
Each progra m line can co ntain at most 79 characte rs.
Program lines can be entered in any sequence.
RPBASIC-52 properly orders line numbers.
Functions return a value u sed for c omp utation .
Exam ples ar e AIN , PEEK, SIN , and COM $.
Functions do not cause a change in an output.
Line Numbers
Program line s begin with a unique line number.
Each line number m ay contain on e or more B asic
statements separated by a colon. Line num bers are
in the range of 1 - 65535.
Operators
Operators act on or convert num eric or s tring da ta.
These include arithmetic (+,-,*, and /), natural
logarithmic (base "e"), trig (SIN, COS), relational
(>, <, or <>), logical (.AND., .OR., .XOR.), and
string (ASC, STR) functions. Special operators
control the hardware-specific features of RPBASIC52 such as interrupts, timers, counters, and direct
read/write of I/O ports.
Tasking Statements
Multiple statements on a single line are allowed
when statements are separated by colon (:) and do
not exceed a total of 79 cha racters per pro gram line.
Ending a program line with a colon may cause a
program to hang.
There are two ways to write Basic programs. The
first way is to directly type in the program to the
card. All standard Remote Processing cards have a
means of sto ring pro gram s to a fla sh type EPR OM .
The second way is use a text editor and download
the resulting file to the system. Just be sure to save
files in DOS text format.
Downloading programs means transferring them
from your PC (or M AC or term inal) to the card.
Uploading means transferring them from the card
back to the PC.
When uploading or dow nloading files, select A SCII
text format. XMODEM , YMODEM , or other
formats are not used. RPBASIC-52 does not know
when you are typing in a program or if something
1-2
Page 6
RPBASIC-52 PROGRAMMING GUIDE
else (laptop or main fram e) is sen ding it c harac ters.
The upload and download file does not contain any
special codes; they are simply ASCII characters.
Uploading programs is simply a process of receiving
an ASC II file. You or your program simply need to
send "LIST" to receive the entire program.
Downloading a program requires transmitting an
ASCII file. As you type in (or download) a line,
RPBASIC-52 tokenizes that line. The time to do
this depends upon its complexity and how many
lines of code have been entered.
RPBASIC-52 must finish compiling a line before
starting the next one. When a line is compiled, a ">"
character is sent. This should be your terminal
programs pacing character when downloading a
program.
If your comm unications progra m canno t look for a
pacing prompt, set it to delay transmission after each
line is sent. A 100 ms delay is usually adequate, but
your program may be long and com plex and require
more time. A result of short transm ission time is
missing or incomplete program lines.
gone. Downloading tim e is increased w hen the old
program is still prese nt.
If you like to write programs in separate modules,
you can dow nload them separately. M odules are
assigned blocks of line numbers. Start up code
might be from 1 to 999. Interrupt handling (keypad,
serial ports) m ight be from l ines 10 00 to 14 99.
Display output might be from 1500 to 2500. The
programmer must determine the number of lines
required for each section.
RPBASIC-52 automatically formats a line for
minimum code space. For example, you could
download the following line of code:
10 fora=0to5
When you listed this line, it would appear as:
10 FOR A=0 TO 5
Spaces are displayed but not stored. The following
line:
10 for a = 0 to 5
A technique used to further program documentation
and reduce code space is the use of comments
(REM) in a downloaded file. For example, you
could have the following in a file written on your
editor:
REM Check position
REM Read output from the pot and
REM calculate the position
2200 a = ain(0) :REM Get position
The first 3 comments dow nloaded to the c ard
are ignored. Similarly, the empty lines between
comm ents are also ignore d. Line 2200, w ith its
comment, is a part of the program and could be
listed. The major penalty by w riting a program this
way is increased download time.
Notice that you can write a program in lower case
characters. RPBASIC-52 translates them to upper
case.
Some programm ers put "NE W" as the first line in
the file. During debugging, it is comm on to insert
"temporary" lines. This ensures that these lines are
would be compressed and displayed as in the second
example above. Spaces are removed. How ever,
spaces as part of a remark or PRINT are not
removed.
RPBASIC-52 contains no line renumbering
capability.
RPBASIC-52 contains a rudimentary line editor
which allows editing a program line until a carriage
return is sent. The rubout or backspace key can be
used to delete characters working backwards form
the current character. After a line is entered, it
cannot be edited; you m ust ent er an e ntire ne w line .
Deleting an undesired line is done by typing the line
number followed by a carriage return. RPBASIC-52
automatically deletes all such lines.
Upperca se/Lower case
RPB ASIC -52 is ge nerally not ca se-sen sitive.
Program or comm and lines m ay be entered in
lowercase or uppercase; however they are (with
some exceptions) converted to uppercase. The case
of text in remarks and strings is preserved.
1-3
Page 7
RPBASIC-52 PROGRAMMING GUIDE
Variables and Con stants
More than 25,000 unique variable or constant names
may be defined. Names may be up to eight
characters in length and must begin with a letter
between A -Z (no num bers or s pecia l chara cters).
The rest of the name may contain numbers or letters
and include the underline character.
All numeric variables are floating point. Variables
cannot be declared as inte ger or d ouble precis ion.
RPBASIC-52 supports eight digits plus sign and
exponent. Extra digits are simply discarded. The
range of valid values is ± 1E-127 to
±0.99999999E+127.
Names are identified by the first and last characters
and its length. Identical length names with identical
first and last characte rs are c onside red the sam e.
PUM P_42 and P RIM ER2 are co nsider ed the sam e.
The way to correct this is to change the nam e length
or first or last character.
Variable names longer than two characters require
more time to process. Once a variable name is
declared, it can only be erased by the CLEAR
statement or by LOADing in a new program.
It is possible to have variable names longer than 8
characters. A problem is the name length is stored
partly as a modulo 256 number. What it boils down
to is a variable may or may not be recognized as
unique. The Basic considers FEED_BIN_01 and
FEED_BIN_11 as the same variable.
The original B ASIC-5 2 had a bug w here the variable
name 'F' was erased if it was the last letter in a
variable followed by a space. RPBASIC-52
corrected this.
SIZE(5), ABC_
Invalid variables, which may include embedded
commands include:
4C, C$0, GOTOE, FORM, #XYZ, _ABC
Constants are literal values. These are "known"
values as opposed to variables which can be
assigned any value, usually by a function. Constants
may be numeric or string. To RPBASIC, there is no
difference between the two.
Constants are expressed as integer, decimal,
hexadecimal or exponential floating-point. The
range of valid values are:
± 1E-127 to ± .99999999e+127
Using constants instead of a number speeds up
execution by at least 5%. For exam ple, use
10 CH = 5
20 A = AIN(CH)
instead of
20 A = AIN(5)
Variables and constants are expressed as follows:
A = 5Integer format
A = 5.3Decimal format
A = 0ACHHexadecimal format
A = 1.4E3Exponential
RPBASIC-52 supports eight significant digits plus
and exponen t and tru ncate s any e xtra digits.
Hexadecimal constants with a leading alpha
character must be preceded by a leading zero. If you
fail to do this, RPBASIC-52 interprets them as
variable nam es.
Watch out for comm ands em bedded in va riable
names. FO RM _5 con tains the com man d FO R. A
BAD SYNTAX error is usually returned in these
instances. The statement FORM_5=BOTTOM does
not return an error but interprets it as
FOR M_5=BOT TO M
The key is to look at your statem ents as they are
printed on the screen and make sure they are what
you intended.
Valid variables names are:
CA5, DA15_679, PUMP_A, VALVE02, A(10),
All hexadecimal constants are followed by a trailing
"H" (0FFH for exam ple). A "0" prefix is ne cessary
when the first num ber is a letter (A -F).
Certain logic al ope rators, su ch as .N OT., .AND.,
.XOR., and .OR., assume a 16-bit argument such as
0FFFFH. If you supply fewer than 16 bits, it returns
a 16-bit value based on the assumption the
unsupplied most significant bits are zero.
Subroutines
Use of subroutines tends to make programming
more modular and easier to follow. The number of
1-4
Page 8
RPBASIC-52 PROGRAMMING GUIDE
subroutines is limited to the amount of internal stack
space. Usually this is about 35 subroutines, but can
go down if FOR-NEXT loops are active. This is
sufficient to handle all multi-tasking (ON LINE, ON
COUNT, ON KEY PAD, etc.) and several levels of
subroutines.
Most complex programs tend to have a maximum of
7 nested subroutine levels. Usually the maxim um is
4.
Passing Variables Between Programs
All variables in R PBA SIC-52 are g lobal. This
means any routine can modify any variable at any
time. When a new program is loaded using
EXECU TE, variables are erased.
Values can be passed between programs using any
variations of PEEK and POKE statem ents.
Addresses
Addresses are specified as either decimal or
hexadecim al numbe rs. Hexadec imal addres ses with
a leading alpha character need a preceding zero
otherwise they will be interpreted as variable names.
100POKEB,1,1000H,15
110 A = PEEKB(1,1000H)
Arrays are single dimension and start with element
0. They are dim ensioned using the DIM statement.
Each variable may have up to 255 elements (0 to
254). Undimensioned arrays default to 11 elem ents,
variable(0) through variable (10). Naming
conventions used for scaler variables apply to arrays.
Strings
Memory is allocated to strings using the STRING
command. There is no power up default. Up to 255
strings, identified as $(0) through $(254) are
available.
To use strings, you must first determine the
maximum length of any one string and then the
maximum num ber of strings. Using the formula
(bytes/string + 1) * number of strings + 1
returns the number of bytes to allocate.
The ASC, CHR, and ST R com mands a re used to
evaluate and manipulate strings. Text assigned to a
string is enclosed in double quotation marks:
100 STRING 1000,40
110 $(0)=">03"
Memory addresses range from 0 to 0FFFFH and
segments from 0 to 7. A segment represents a 64K
block of memory. Programs and RPBASIC-52
variables reside in segment 0. Variables are
generally stored in segment 1 and higher.
RPBASIC-52 Memory Map
Basic program area can be 32K or 64K, depending
upon the am ount o f RA M ins talled .
Arrays
1-5
Page 9
RPBASIC-52 PROGRAMMING GUIDE
OPERATING MODES
Command and Run M odes
RPBASIC-52 operates in two modes, Command and
Run. Command mode is the direct, interactive mode
accessed when RPBASIC-52 is not running a
program. The Basic console prompt ">" indicates
that Basic is ready for Comm and m ode input.
Run mode is when the processor is activ ely
executing a Basic program. Some commands (such
as SAVE, LIST, LOAD) can only be executed when
the processor is in command mode. Most Basic
instructions can be executed in either Command or
Run mode.
In Command mode, LOAD selects a Basic program
from the flash. The RUN command then causes the
selected program to execute. Within a B asic
program, the EXECUTE instruction is used to allow
the currently running program to call another stored
program. A number of programs m ay be availab le
to run depending upon the card and flash EPROM
size installed. Refer to your hardware manual for
more information.
Autorunning Programs
which halts output to the console serial port only;
<Ctrl-Q> (X-ON) restarts it. You can use this
feature to prevent screens of output data from
scrolling by too quickly to read. After you type a
<Ctrl-S>, Basic halts program execution if it is
encountered during a PRINT com mand un til it
receives a <Ctrl-Q>. You can also reduce the serial
port baud rate or use the NULL com mand to slow
down the output of console data. Be careful of the
NULL command. Some term inal program s print a
space character instead.
Characters are buffered from th e seria l port.
Therefore an additional 256 characters may continue
to print after a <Ctrl-S> is sent.
WARNING:Program execution halts during a
PRINT when an X -OFF is
received until a X-O N is re ceive d.
This means no other Basic
comm ands are exe cuted. Multitasking interrupts are recognized
but not executed until after the
PRINT statement is finished.
To determine if X-OFF is active (printing halted)
before executing a PRINT statement, check address
38, bit 5. If high, X-OFF is active.
Programs may automatically load and run on
powerup or reset when a specific jumper is removed
on the card. Refer to your card's hardware manual
for more information on jumper location.
When autorun is enabled, a LOAD 0, RUN sequence
is performed on power up or reset. Programs are
chained using the EXECUTE command.
Stopping Program Execution
<Ctrl-C> halts the execution of a program and forces
the processor into Command mode (unless <Ctrl-C>
has been disabled). Operation can be resumed by
typing the CONT comm and. The STOP instruction
stops a running program; execution resumes with a
CONT command.
Sometimes it is desirable to not stop program
execution. To disable <Ctrl-C>, execute:
DBY(38) = DBY(38) .OR. 1
X-ON and X-Off Flow Control
100 IF (DBY(38) .AND. 32) = 0 THEN 200
Normally the result of the above test is 0 (no X-OFF
received) and the program branches to line 200. Of
course, if X-OFF is received during a PRINT
command, program execution is suspended until an
X-ON is received. To clear X-OFF (due to a
protocol you are using), put the following line in:
120 DBY(38) = DBY(38) .AND. 0DFH
STORING PROGRAMS
RPBASIC-52 programs are stored in non-volatile
flash type EPROM . The SA VE co mmand is used to
write programs from RAM while LOAD retrieves
them into RAM. Depending upon the card and the
EPROM type installed, up to 8 programs can be
saved and loaded. Refer to your card's hardware
manual for specific programming information.
Serial output can be stopped w ith <Ctr-S> (X-OFF ),
1-6
Page 10
RPBASIC-52 PROGRAMMING GUIDE
HARDWARE AND SOFTWARE
INTERRUPTS
RPBASIC52 generates two kinds of interrupts:
hardware and software. Hardware types are those
generated by a voltage change and go directly to the
processor. Software types require program execution
and set memory flags that are read by some other
program.
NOTE: Not all products support all or the same
interrupts. Make sure the "Cards:" category
in each command lists your card or re fer to
your hardware manual.
There are six interrupts in RPBASIC-52, version 1.11
and later. In the unlikely scenario that all interrupt
conditions are met at exactly the same time, they
would be serviced in the following order:
ONTICKPeriodic
ONITRExternal line
ON COUNTCounter
ON LINELine change
ON COM$Serial input
ON KEYPADKeypad
Interrupt priority is based on hardware or software
type. ONTICK and ONITR are considered hardware
types. Should either one of these interrupts become
active, ON COUNT, ON LINE , ON KEY PAD, and
ON COM$ interrupts are n ot run until either o ne is
finished. If an ONTICK interrupt is running, an
ONIT R interrupt is no t serviced until O NTICK is
complete. ONTICK and ONIT R have the highest
priority.
"typical" time in RPBASIC is less than 1 ms.
However, it can be as short as several micro-seconds
to several seconds. The reason it can take so long is
due to the Basic subroutine. Suppose an ONTICK
interrupt is in progress and it is written so it takes
several seconds to complete. Since it is the highest
priority, all other interrupts are locked out. The best
way to correct this situation is to make all interrupt
routines as short as possible. This is handled by
setting a flag using a variable in the interrupt routine
then exiting. Then at some other non-critical time,
the interrupt is serviced.
WARNING:RPBASIC-52 offers a op portunity
for all interrupts to occur
simultaneously. It can handle all 21
interrupts simultaneously.
However, it cannot handle them
when they occur at a rate faster than
they are serviced. Servicing all 21
interrupts requires a minimum of 21
ms. If interrupts consistently come
in faster than they can be handled,
the program will stop and a control
stack error returned.
Whenever an ON COUNT or ON LINE multitasking
command is enabled, overall program speed slows
down. If all ON COUNT and ON LINE in terrupts
were enabled (but lines were not changing), program
speed slows down by about 6%.
ON COUN T, ON LINE, a nd ON COM $ interrupts
are serviced after ONT ICK and ONIT R are com plete.
Should any these last three interrupts occur
simultaneously, ON COUN T would be execute d first.
However, if any of these three interrupts occur after
one has started, then it would take priority.
Interrupts occur any time during program execu tion.
The RP BASIC operating sys tem sets app ropriate
flags indicating which kind of interrupt needs
services. At the end of the current statement it checks
these flags. The time interval between the actual
interrupt and start of the interrupt routine is called
latency.
Latency varies a great deal, depending upon the type
of interrupt and command currently executed. A
1-7
Page 11
RPBASIC-52 PROGRAMMING GUIDE
MULTITASKING CONSTRUCTS
COUNT M ultitasking
RPBASIC-52 on the RPC-3XX series of cards can
count pulses while a program is running. Checking
and counting is performed at assembly language
speed during each system tick time (every 5 ms).
This capability effectively speeds up program
performance and simplifies programming.
This section describes only software counters on the
card. Hardware counters are in a separate category
are disc usse d in the h ard war e se ctio n of t he c ard's
manual.
Just about any valid digital I/O line can be designated
as a counter input. Exceptions are interrupt inputs,
keypad, and display lines. Even if a digital line is an
output, it can be designated as a counter input. This
is useful in situation where you may want to limit or
keep track of the number of pulses to a motor,
solenoid, or lamp.
Eight software counters are available. They are
numbered 4-11. Counters 0-3 are reserved for any
hardware ones that may or may not be on your board.
Counting is enabled as soon as a line is designated as
a counter using ON C OUN T. The digital line is
sampled every 5 ms. When it goes from a high to low
state, its counter is incremented. A line must be
sampled at a high state before it can be counted again.
A line must be at a high and low state for a minimum
of 5 ms each to ensure detection. In theory the
maximum counting rate is 100 Hz. However, due to
other multitasking events (mainly serial ports),
effective maximum rate is about 95 Hz assuming a
perfect square wave.
There are two commands used in COUNT
multitasking: COUNT and ON COUNT. Notice
there are two COUNT commands. One is a function,
which returns a value. This is the one used by the
software counters. The other COUN T comm and is a
statement, which writes a value to a hardware
counter. This is not used by the software co unters.
Software counters canno t be preset.
ON COU NT declares or clears a multitasking
process. T here are thre e variations o f this comma nd.
Referring to the ON C OUN T com mand in this
manual, the first syntax defines the digital line to
count, number of pulses to count before executing a
subroutine. When the specified number of pulses is
reached, the counter resets and a count interrupt flag
is set. Should a higher priority interrupt be executing,
the count subroutine is delayed until the higher one is
finished. The COUNT func tion is not usually use d in
conjunction with this version.
The second syntax simply declares a line for
counting. Use the COUNT function to return the
number of pulses at the line. When the count reaches
65,535 it rolls over to 0. To reset o r clear a cou nt,
simply re-declare the ON COUNT statement for that
line.
The third syntax shuts off multitasking for that
counter.
The ON COUNT command can be used to expand
the number of lines used as an ON LINE command.
The limitation here is an interrupt is generated only
when a line goes low. Set the count to 1 in the ON
COUNT declaration.
Serial Communication Multitasking
ON COM $ defines a program branch when either a
specific character or number of characters is met.
Criteria are specified in the O N CO M$ state ment.
When the criteria is met, the incoming data is referred
to as a packet.
This statement is especially useful in a networking
application using the RS-485 serial port. Other
devices, such as modems or scales can be used to
generate an interrupt using RS-232. A ll serial ports
can use ON COM$.
Data packets are retrieved using the COM $ function.
In RS-485 networking applications, the STR (8,...)
function is useful for determining its address.
Two serial application program s are in this manu al.
The first program is a simple RS-485 network
communication handler, shown in Appendix A. The
second uses a modem to auto receive and is in
Appendix B.
The RS-485 network handler is set up as a masterslave protocol. Slaves "do not talk unless spoken to".
The host transmits to all receivers. All receivers
transmitters go to the hosts receive line. The host
does not transmit until it receives a response from a
node or a timeout is reached.
1-8
Page 12
RPBASIC-52 PROGRAMMING GUIDE
There are many communication protocols. For this
example, the protocol looks something like this:
>03MB1
The protocol starts with the <cr> cha racter. This
character synchronizes all units and alerts them that
the next few characters coming down are address and
data. In this case, ">03" is the nodes address. Next
follows a command (M). Depending upon the
command, data may or may not follow. An optional
checksum may follow. The figure below shows the
elements in a data packet.
the RPC-3xx series cards. Refer to this program for
the following description.
The program starting at line 1000 is the network
command handler. Line 1000 gets the data packet.
Line 1010 determines if it is meant for this card.
Commands are sorted, or parsed out beginning at line
1020. For this examp le, comma nds are assu med to
begin with the letter 'A'. By subtracting the ASCII
value of A, we set up the ON GO TO struc ture to
quickly handle each com mand type . This samp le
assumes 5 commands. If more are desired, another
ON GOTO can be used. The start of the statement
could read: ON OA-5 GOTO
linenum ber,linenumber,line number...
Command types can be broken into two groups: The
first group performs an action such as setting a line,
outputting to the display, or begin a complex timing
process. The second group is a function, which
returns data. This data can either be raw, such as a
line status or voltage input, or processed. Processed
data can be averages, converted values (feet/minute),
operator input from a keypad, or a status report (such
as OK) to determine if the board is there and
functioning. The intent of these commands is to show
how data is converted from string to number or
number to string.
The response depends upon the nature of the
command. Suppose the command M means "return
door switch status". The card could read the port and
respond with A1<cr>. The first letter A is an
acknowledge. Data, 1, indicates a high.
Errors are returned with the letter N (negative
acknowledge) followed by a number. The number
identifies the general error type.
The program in Appendix A can be used on any of
This example uses the following commands:
CommandAssociatedFunction
Data
A1 or 0Set line 8
Bline, analog Motor speed
output 0 to
4095
C0-1Position from counter
DStringPrint to display
E(none)Power up
acknowledge
F(none)General status
Command E is very useful to implement in situations
where the host does not know if a unit reset (due to a
power surge or something). The host may make
certain assumptions about the status of a unit and
continue to issue commands based on invalid
assumptions. Lines that were set before may not be
set.
This program is written so that no com mand is
1-9
Page 13
RPBASIC-52 PROGRAMMING GUIDE
processed unless the host "knows" this node has just
reset. Any valid command, unless it is "E", returns a
"N2" negative acknowledgement. The host
recognizes this as a power up condition. Line 1220
checks for a valid power up flag.
Command F could return any number of status
conditions. The way it is implemented here, data is
returned to indicate the type of error. A 0 return
indicates things are just fine. The type and value of
data returned will depend upon the number of error
conditions. If error conditions were binary weighted
(1, 2, 4, 8...) then the receiver could determine
exactly what errors are in the system.
A unique address in the message packet, >99 , tells all
units using this program to go to a 'safety' mode. It is
used for emergency shut down situations. Nodes do
not reply to this command. The program example
does a simple return as your application determines
appropriate respon se. The ad vantage to u sing this
command is in emergency situations all units get the
message in under 50 ms. It could take considerably
longer, perhaps 1 second in a 20 node system , to poll
all units.
COM1 is set as the receive port. The modem
connects to the RPC card serial port using a VTC-9F
serial cable. Most external modems have a DB-25F
(female) connector for the serial port, therefore a DB9F to DB -25M adapter is ne cessary. Also , since both
the RPC card and modem are designed to plug into a
PC, a null modem adapter must be inserted between
the DB-9 connector on the VTC-9F and adapter. The
connectors are shown below:
modem > DB9F to DB-25M > null modem > VTC-9F
This can be somewhat of a kludge. A nother way is
to make a custom cable from the R PC card 1 0 pin
IDC connector to a DB -25M. If you ch oose this
route, connect the pins in the following manner:
A networking factor is communication time. Longer
messages take longer to p rocess. At 9 600 ba ud, it
takes about 12 ms to send out a 10 character m essage.
This assumes the host can assemble a message string
instantaneously. Add 5 ms processing time by the
remote card (and 5 ms could be considered a
minimum) before anything is sent out. It could be
nearly 50 ms for a complete exchange. Using a
simple command structure, about 20 message
exchanges per second are possible.
Increasing the baud rate decreases message exchange
time, but there is a point of diminishing return. Going
to 19,200 baud cuts serial communication time in
half. However, message processing time stays the
same. At some point in time the processing power of
the host and remote units is a major factor. RPC
cards process comm ands roug hly at a rate of 1/m s.
To verify an address and begin ca rrying out a
command takes about 30 ms. Any additional data
processing increases this time.
The next application in Appendix B uses a modem in
a receive application. T his illustration uses a g eneric
1200 baud modem, although a higher speed modem
can be used provided incoming data do es not com e in
so fast the buffer fills and characters are lost.
Your modem may have configuration switches. Set
these switches to the following conditions to use the
sample program:
Force DTR lead (pin 20) true to enable modem
to execute commands.
Modem responds to commands with english
word result codes.
Result codes sent to the RPC card.
Echo characters while in the command state.
Modem automatically answers an incoming
call.
Force CD lead (pin 8) true.
Enable modem command recognition.
You may have to set these conditions in software.
There is a certain sequence, or protocol, that is
followed when answering a phone. The steps
(CYCLE) follows:
CYCLEAction
1-10
Page 14
RPBASIC-52 PROGRAMMING GUIDE
0Wait for "RING" message. Modem
auto answers.
1Look for "CONNE CT".
2Get password. If invalid, prompt for
password again.
3Send successful log in me ssage .
Prompt for comm and and process
them.
4Take modem off line and reset
5Delay for a few seconds and send sign
on message.
The actual program is more complicated than the
steps indicate. Timeouts are used to disconnect the
modem when there is inactivity. Three failed
passw ord atte mpts takes t he m odem off line.
Ringing but no connect takes the modem off line.
Superfluous <cr>'s are ignored.
Activity timeout is set for 10 seconds. The
ONTICK routine checks for activity every second
when the program cycle advances to step 1 and
beyond. ON TIC K cou ld be fa ster if it is necessary.
Keep in mind that ONTICK interrupts have the
highest priority. Keep tick interrupt processing
times short and as infrequent as possible. Frequent
and/or long processing times take away from other
program times.
ON COM $ interrupt uses a program cycle pointer
(variable CYCLE) to direct the next activity on an
interrupt. When a message is received, an interrupt
is generated. Processing the message is handled by
the appropriate routine poi nted to by CY CLE . A
<cr><lf> sequence is simply ignored and treated as a
non-event.
After the password is accepted, the main purpose of
the application takes over. There are many
scenarios, or situations, possible:
1. The c omputer is used for d ata log ging.
Dialing in merely dumps data.
2. The computer is used for control. A dial up
is for new instructions or parameters.
3. Some combination of data logging and
control.
4. A computer will dial up and query and/or
issue new instructions.
5. A person using a terminal will dial up the
control card and query and/or issue new
instructions.
6. A com puter and/or person at a terminal w ill
dial up and query and/or issue new
instructions.
7. A new program is downloaded to the card.
The number of possible applications is much too
complex to even begin showing code.
Some applications use a person at a term inal to
remotely query the card. In this situation, it is nice
to return a character as soon as it is typed in. This
can be done by setting the users terminal to local
echo. However, you don't know if the card received
what you send. The remote card can echo back
characters as they are sent. To do this requires a
program change. ON COM $ must either be disabled
or changed to generate an interrupt on each character
input. If ON COM$ is disabled, then the m ain
program has to be structured so it can process
incom ing ch aracte rs imm ediately.
If ON COM$ generates an interrupt on each
character, then the incoming data rate should be
relatively slow (1 character every 50 ms). Note this
is not the baud rate. Th e baud rate ca n still be 9600.
It just should not get characters more than 20
times/second. For hand typing situations, this is just
fine.
When another computer is talking to the card,
immediate echo may not be necessary. Instead, the
incoming message can be echoed back w hen a <cr>
is received (or when ON COM$ generates an
interrupt). The cycles would merely increase based
on the command. In some ways, it becomes like a
RS-485 network described above. A comm and is
received, parsed, and processed.
Scenario 7 requires some cautionary notes. It is not
unusual to download program s throug h a m odem .
There is no difference between a modem down load
and one directly connected to a PC. The UI and UO
commands must be set to 1 when using COM 1 and
before going into the command mode (executing an
END or STOP statement in th e program ).
A problem arises when communication is lost for
some reason. While the RPC cards have a watch
dog timer, they are not enabled during command
mode (This is true of the RPC-320 and RPC-330.)
When comm unication is lost, usually a ll that is
required is to redial the modem, assuming it has
been set to auto answer. If communication is lost
due to some external force (cell phone or netw ork
failure), the card will just sit there an d not ru n.
When the application is mission critical, an external
1-11
Page 15
RPBASIC-52 PROGRAMMING GUIDE
watchdog timer may be nec essary to resta rt the ca rd.
Make sure call waiting is disabled.
ON LINE Multitasking
ON LINE is used to detect changes in a line. An
interrupt is generated every time a line goes high or
low. Use this command to detect changes in safety
interlocks, level switches, or process command
switches. Using this multitasking statement saves
code and time because checking is done
automatically in the background. A line must be
high or low for a m inimum of 5 ms to ensu re
detection to another state. Up to 8 lines can be
monitored at one time.
This command is re-entrant, meaning when a routine
is long enough and change interval short enough the
interrupt is called twice. When there is this
potential, the first part of your program should
branch to routines that handle high and low line
conditions. Use the LINE function to return the
current status of a line.
ON COUNT can be used to expand the number of
line changes. Simply specify a count of 1. An
interrupt is generated when the line goes low.
Program execution slows down by up to 5% when
all ON COUN T and O N LIN E statem ents are
enabled.
all ON COUN T and O N LIN E statem ents are
enabled.
Assembly Language Interface
Assembly language programs must be placed in the
RPBASIC-52 EPROM. When using the Basic,
assembly language program s should start at address
6000H or higher, up to 7FFFH.
Norm ally a 3 2K E PRO M is u sed to s tore R PBA SIC.
A 64K EPROM may be used provided a
modification is performed. Refer to your hardw are
manual under ASSEMBLY LANGUAGE INTERFACE
for information.
Documented assembly language interface calls listed
in the Intel MCS BASIC-52 Users Manual will not
work with RPB ASIC-52. This is because
RPBASIC-52 has be reassembled and code shifted
around.
Assembly language development environment
An economical way to development assembly
language programs and still keep RPB ASIC-5 2 is to
use an EPROM emulator. These are available from
several sources.
Up to 65,535 pulses can be counted on any one of
eight lines. A line m ust be both low and high for a
minimum of 5 ms to ensure counting. Maximum
reliable counting rate is 95 Hz.
Counters specified in this statement are software
counters only. It is not related to any hardware
counters on the card.
A number of syntaxes allow simple counting to
interrupt generation when a number of counts is
reached.
The number of counters can be increased by using
ON LINE. Counting rate must be very slow (less
than 10 time s/seco nd) to e ffectiv ely use this method.
A counter increments when a line is low. Use the
LINE function to read the status of a line.
Program execution slows down by up to 5% when
Model types frequently changes, so it is best to
contact these com panie s for the latest in formation.
Generally, these cards connect to the parallel port on
a PC. Downloading a program is generally under 1
second.
The way programs are developed would be to
remove the RPBASIC-52 EPROM and read it by an
EPROM programmer. Save the file.
Install the EPROM emulator into the card. Then,
load in both the RPBASIC-52 binary file and your
assembly language binary file using the software
provided by the emulator.
Assembly language routines are accessed using the
Basic CALL command.
Another development method is to use an In-CircuitEmulator (ICE). Which type you use depends upon
the processor type and your budget.
The precedence of operators determines the order in
which mathematical operations are e xecuted. Ba sic
scans an expression from left to right and performs
no operations until it encounters an operator of
lower or equal precedence. For instance,
multiplication takes prec eden ce ove r additi on.
Parenthetical expressions have the highest
precedence.
The following list is Basic's order of precedence:
1. Operators in parenthesis
2. Exponential operators (**)
3. Negation (-)
4. Multiplication (*) and division (/)
5. Addition (+) and Subtraction (-)
6. Relational expressions (=, <>, <=, <, >=, >)
7. .AND. (logical AND)
8. .OR. (logical OR)
9. .XOR. (logical XOR)
commands and are no longer available:
CLEAR I
CLOCK0
CLOCK1
FPROG through FPROG6
IP
PORT1
PROG through PROG6
RAM
RCAP2
ROM
RROM
TIMER1
TIMER2
T2CON
XFER
XTAL
The following comm ands have b een mod ified with
respect to name and operation:
Parenthetical expressions have the highest
precedence, so their use is a good way for you to
reduce ambiguity and m ake your progra ms m ore
readable. However, parenthetical expressions use
internal data memory.
-subtraction, not negation
*multiplication
/division
**exponential
OBSOLETE and MODIFIED
COMMANDS
A number of commands in the original BASIC-52
have been replaced, obsolete, or no longer
functional. The following is a list of obsolete
1-13
Page 17
RPBASIC-52 PROGRAMMING GUIDE
Some com mands have bee n added to or otherwise
enhanced:
IDLE
INPUT
PWM
The followin g com mands are n ew to BA SIC-5 2.
Note that not all commands/functions are available
on all cards.
AIN
BLOAD
BSAVE
CARD$
CLEAR COM
CLEAR DISPLAY
CLEAR KEYPAD
CLEAR TICK
COM
COM$
COUNT
DATE
DISPL AY
EXECUTE
KEYPAD
LINE
LOAD
ON COM$
ON COUNT
ONITR
ON KEYPAD
ON LINE
ONTICK
PEEK
POKE
SAVE
SPROM
STR
TICK
TIME
WDOG
CONFIG
COMMAND GROUPS
The Comm and Reference is a detailed description of
each RPBASIC-52 command, function, and
instruction. Note that not all cards implement all
comm ands. Also, this list is accura te as of the date
of printing. Newer cards may not make it into this
programming guide.
The following is a list of commands grouped by
function.
Listing and control
LIST
LOAD
NEW
RUN
STOP
SAVE
Multitasking
ON COM$
ONITR
ONTICK
ON LINE
ON COUNT
ON KEYPAD
Program flow and looping
DO-WHILE
DO-U NTIL
END
FOR-TO-NEXT
GOSUB
GOTO
ON-GOSUB
ON-GOTO
REM
RETURN
RETI
1-14
Page 18
RPBASIC-52 PROGRAMMING GUIDE
Data storage and retrieval
BLOAD
BSAVE
CBY
DBY
DATA
DIM
POKE
PEEK
READ
RESTORE
XBY
Operators
/
+
*
**
<
<=
<>
=
>
>=
ABS
AND
ATN
COS
EXP
INT
LOG
NOT
OR
PI
RND
SGN
SIN
TAN
XOR
The trigonometric operators SIN, COS, and TAN
use a Taylor series. Results are calculated to seven
significant digits. The algorithm reduces the
expression to a value between zero and PI/2 and
results in a loss of precision if input_expr is large.
Relational operators (=, <>, <, etc.) return a result of
65535 if the relation is true and zero if it's false. The
result may be displayed or used in further
calculations. Beware when comparing calculated
floating-point values as rounding errors may produce
unexpected results.
Logical operators perform bitwise operations on
expressions which evaluate to valid positive intege rs
between OH and OFFFFFH (65535). All noninteger value s are tru ncate d to inte gers.
Hexadecimal values with a leading alpha character
must be preceded by a leading zero or B asic will
interpret your constant as a variable name. If you
supply fewer than 16 bits to NOT it will return a 16bit value based on the assumption the unsupplied
bits were zeros.
Serial input/output
CONFIG BAUD
COM
COM$
GET
INPUT
ON COM$
UI
UO
Printing and formatting
CR
PRIN T, P., ?
PH
SPC
USING
Hardware input/output
AIN
AOT
CARD$
COUNT
DATE
DISPL AY
KEYPAD
LINE
ON COUNT
ONITR
ON KEYPAD
ON LINE
PWM
TIME
Real time controls
EXECUTE
IDLE
TICK
WDOG
1-15
Page 19
RPBASIC-52 PROGRAMMING GUIDE
String operation
ASC
CHR
STR
STRING
Strings in RPBASIC-52 are one-dimensional arrays
of characters. Strings are stored as a sequence of
ASCII values terminated with a 0D H (the AS CII
value of a carriage return).
Memory for strings is allocated by the STRING
operator. String varia bles ar e $(0) th rough $(254) .
Strings may be any length, lim ited only by ava ilable
memory. However, if you wish to assign a string to
explicit text in quotes, it may be up to
[72-{number of digits in string identifier}]
characters in length. In other words, $(9) may be 71
characters long, but $(200) may be only 69
characters long. This is due to the BASIC-52
program line length limit of 79 characters. Longer
strings must be assigned one character at a time with
the ASC operator or the X BY instruc tion. Explicit
text assigned to a string must be enclosed in double
quotation marks. The ASC and CHR operators can
evaluate individual characters in a string.
Interrupts
ON COM$
ON COUNT
ONITR
ON KEYPAD
ON LINE
ONTICK
RETI
Other operators
IDLE
Memory Allocation
FREE
LEN
MTOP
1-16
Page 20
RPBASIC-52 PROGRAMMING GUIDE
ABS
Syntax:ABS(expr)
Where: expr = any number in Basic's range
Function:Returns the absolute value of an expression
Mode:Command, run
Use:PRINT ABS(C)
Cards:All
DESCRIPTION
The absolute value of a number is always positive or zero.
2-1
Page 21
RPBASIC-52 PROGRAMMING GUIDE
AIN
Syntax:AIN(channel)
Where: channel = 0 to 7, is channel to convert.
Function:Converts analog input to digital number and returns a number from 0 to 4095 (0 to 1023 for the RPC-
52)
Mode:Command, Run
Use:B = AIN(N)
Cards:RPC-52, RPC-320, RPC -330. RPC -52 range is 0 to 102 3 (10 bit).
DESCRIPTION
AIN returns a number corresponding to the input voltage. A number from 0 to 4095 (0 to 1023 for RPC-52)
is returned. The result is returned in under 2 ms. Input voltage may be 0-5V or ±2.5 volts, single ended or
differential. Inputs are configured for 0-5V, single ended input on power up. Use CON FIG AIN to configure
each channel's cha racteri stics.
The RPC-52 does not have differential inputs or use CONFIG AIN. Refer to the RPC-52 hardware manual
for more information. The following explaination assumes a 12 bit result (0 to 4095) is returned.
A result is scaled to obtain a result representing a physical quantity. The general equation is:
variable = K * AIN(n)
where K is a scaling constant and n is the channel number. The scaling constant is determined as follows:
K = (maximum quantity - minimum quantity) / 4096
The physica l quan tity can be vol ts, curre nt, press ure, inches, or w hatev er me asurem ent yo u are ta king.
"maxim um quan tity" is the numb er with its output at 5 v olts while "m inimum quantity" is the num ber at 0
volts. Usually, the minimum quantity is 0.
Suppose you have a 0-200 PSI pressure transducer with a 0-5V output. To compute the constant for one
PSI/count, divide the pressure over the resolution:
K = 200/4096
K = 0.04828 = PSI change per count
To measure 0-5 volts, K = 0.001220703
RELATED
CONFIG AIN
ERRORS
BAD ARGUMENT When channel expr > 7 or negative
BAD SYNTAXWhen channel expr left out
2-2
Page 22
RPBASIC-52 PROGRAMMING GUIDE
ASC
Syntax:ASC(ASCII character)
ASC(string,position expr)
Where: ASCII character = number from 0 to 255
string = any valid string variable
position expr = 1 to length of string
Function:Returns or sets the integer value of an ASCII character or the character in string at position expr.
Mode:Command, run
Use:PRINT ASC (C)
ASC($(3),1)=48H
C = ASC($(0),P)
Cards:All
DESCRIPTION
The ASC operator either sets or returns the value of an ASCII character. Use ASC to evaluate, change or
manipulate individual characters in a string.
The first syntax returns the value of an ASCII character. If ASCII character were the letter 'B', a 66 is
returned. Basic converts any lower case variable symbols to upper case. Lower case characters must be put
into a string to be evaluated.
The second syntax, shown under Use, sets a character in a string to a specific value. This is useful when you
want to manipulate individual characters in a string.
The third syntax returns a value in string at position expr. This form is useful when you want to eva luate
individual characters in a string, such as generating a checksum.
The STR command, unique to RPBA SIC-52, manipulates entire strings.
RELATED
CHR, STR, STRING
ERROR
SYNTAXAttempt to convert an improper value.
EXAMPLE
The following example prints ASCII values from the string $(0). The first 3 characters are modified at lines
70 to 90. The result is then printed.
10 STRING 200,20
20 $(0)="abc123"
30 FOR N=1 TO 6
40 PRINT ASC($(0),N),
50 NEXT
60 PRINT
70 FOR N=1 TO 3
80 ASC($(0),N)=65+N
90 NEXT
100 PRINT $(0)
READY
>RUN
97 98 99 49 50 51
BCD123
2-3
Page 23
RPBASIC-52 PROGRAMMING GUIDE
ATN
Syntax:ATN(expr)
Where: expr = value between 0 and PI/2
Function:Returns a trigonometric arc-tangent of expr. Returned result is between -PI/2 and PI/2 radians.
Mode:Command, run
Use:PRINT 4*AT N(1)
Cards:All
DESCRIPTION
SIN, COS, and TAN operators use a Taylor series to calculate the function. These operators first reduce the
argument to a value that is between 0 and PI/2. The algorithm used to reduce the value will reduce accuracy
when expr is large. To maintain accuracy, keep the arguments for trig functions as small as possible.
ERRORS
ARITH. UNDERFLOW expr or result is less than RPBASIC-52's smallest floating-point value of ±1E-127
ARITH. OVERFLOWexpr or result is greater than RPBASIC-52's largest floating-point value of
±.9999999E+127
DIVIDE BY ZEROAttempt to take TAN(X) when COS(PI/2) = 0
Syntax:BLOAD to RAM segment, RAM address, from EPROM segmen t, EPRO M add ress, length
Where: to RAM segment = 0 to 7, is the 64K block in RAM to write to
RAM a ddress = 0 to 65,535, is the ad dress to write to
from EPROM segment = 0 to 7, is the 64K block in EPROM to read from
EPRO M address = 0 to 65,535, is the address in EPROM to read from
length = 0 to 65,535, is the number of bytes to move from EPROM to RAM
Function:Transfers a block of binary data from flash EPROM to RAM.
Mode:Command, RUN
Use:BLOA D 1,0,5,0,1000
Cards:RPC-320, RPC-330
DESCRIPTION
BLOAD transfers a block of binary information from EPRO M to RAM. BLOAD does not check to see if
there is enough R AM m emory to save to or if the EPR OM is la rge enough to p erform the transfe r. Data is
retrieved from RAM using PEEK type functions.
segment can be though of as the X0000H address of the RAM or EPROM. When a segment of 1 and an
address of 4300H are used, an address equivalent to 14300H is used to access the device. When a 128K
RAM or E PRO M is used, segment is 0 or 1. A 512K RAM or EPROM can have a segment of 0 to 7. A 32K
device only has segment 0.
NOTE: Avoid using RAM segment 0. This is where RPBASIC program and variables are used. When
segment 0 must be used, transfer data to above the MTOP address location.
Data transfer rate is about 23.5 ms/1000 bytes. During BLO AD tim e, ONT ICK and ONITR interrupts are
recognized but not serviced. If these commands must be serviced quicker, transfer data in smaller blocks.
BSAVE transfers data from RAM to flash EPROM.
RELATED
BSAVE, all PEEK commands
ERROR
BAD ARGUMENT When any parameter above is out of limits.
EXAMPLE
The following example POKEs data into segment 1 of data RAM. The data is then saved to EPROM
segment 6 and loaded back to a different location in RAM. The data is then verified. A 128K RAM and
512K flash E PRO M m ust be in stalled for this e xample to w ork.
10 RA=512
20 FOR N=0 TO 1000 STEP 2
30 POKE W1,N,N
40 NEXT
50 FOR N=2000 TO 3000 STEP 2
60 POKE W1,N,0
70 NEXT
80 BSAVE6,RA,1,0,1000
90 BLOAD1,2000,6,RA,1002
100 FOR N=0 TO 1000 STEP 2
110 B=PEEKW(1,N+2000)
120 IF B<>N THEN PRINT "Error address",N," data is",B
130NEXT
2-5
Page 25
RPBASIC-52 PROGRAMMING GUIDE
BSAVE
Syntax:BSAVE to ROM segmen t,ROM address,fro m RA M segm ent, RAM address, length
Where: ROM segment = 0 to 7, the 64K byte block to w rite to
ROM address = 0 to 65535, ad dress to write to
RAM segment = 0 to 7, a 64K byte block to read from
RAM a ddress = 0 to 65535, address to read from
length = 0 to 65535, number of bytes to write
Function:Writes raw binary data to flash EPROM from RAM.
Mode:Command, run
Use:BSAVE 1, ROMTO , 1,RAMPTR , 512
Cards:RPC-320, RPC-330
DESCRIPTION
BSAVE writes a block of binary information to E PRO M from RAM . Use the PO KE com mands to w rite data
to RAM.
WARNING:BSAVE should be used sparingly. The flash EPROM has a limited number of write cycles
(1000) to each sector.
A length of 0 writes 65,536 bytes.
Limited pa rame ter che cking is perfo rmed . Basic assum es RA M exists at the segm ent an d addr ess spe cified.
Basic checks to make sure the ROM segment specified is within limits of the installed EPROM , but addresses
and lengths are not checked.
WARNING:BSAVE can write over programs saved using the SAVE command.
A segment can be though of as the X0000H address of the RAM or EPROM. When a segment of 1 and an
address of 4300H are used, the address equivalent to 14300H is used to access the device. When a 128K
RAM or E PRO M is used, segment is 0 or 1. A 512K RAM or EPROM can have a segment of 0 to 7. A 32K
device only has segment 0 and its address is limited to 32767 decimal, or 7FFFH.
A flash EPROM is written to in sectors. A sector is 64, 128, or 512 bytes for the 32K, 128K, or 512K
EPR OM respec tively. R PBASIC autom atical ly dete cts the type o f EPR OM installe d whe n it writ es to it.
You must pay attention to the sector size for two reasons. First, a sector is the minimum number of bytes
written. If a program requires only 35 bytes to be saved, 512 bytes are w ritten when a 5 12K EP ROM is
installed. If the following is performed
several things happen. The data saved by line 1000 is overwritten by the data in line 2000, even though
different write addresses were specified. Th is bring s us to th e seco nd rea son se ctor siz e is considered.
RPBASIC forces the requested EPROM address down to an even sector address. In both ca ses above, data is
written to the EPROM starting at address 0, not at 5 or 42.
The solution to this situation is to write data out in even sector size blocks and to write them on sector
boundaries.
A program is not required to write in full sector sizes. When less than 1 sector is specified, RPBASIC writes
the next data in RAM until the full sector size is reached. When a large number of bytes are written, covering
2-6
Page 26
RPBASIC-52 PROGRAMMING GUIDE
many sectors, the last written sector is filled in with more data from R AM. N ote that BL OAD allows data
retrieval of any length and is not affected by sector size.
The easiest way to determine an even sector address is to "AND" the EPROM address with either FFC0H,
FF80H, or FE00H for 32K, 128K or 512K EPROMs respectively.
Data can be saved "above" program s. The following is a way to dete rmine the ne xt free sector for writing to
flash.
1) Save the program. Note the number of bytes saved.
2) Add the sector size (based on flash EPROM type) plus 64 bytes to the number of bytes saved. (64
bytes is for program overhead). For example, suppose the program is 28145 bytes long and a 512K
(29C040) EPROM is installed. 28145 + 512 + 64 = 28721
3) At the terminal, print the following:
print 28721 .AND. 0FE00H
the response is
28672
What you have done is told the computer to print the length o f the program + 512 bytes (for the sec tor) +
64 bytes (for program overhead) and 'and' it with FE00H. Notice the address, 28672, is higher than the
number of bytes saved and less than the number we figured for sector size and overhead.
4) BSAVE can be used starting at this address (28672, or 7000H).
This method will work regardless of the number of programs saved or segment numbe r.
Writing takes about 35 ms/1000 bytes. During BSAVE time, ONTICK and ONITR interrupts are recognized
but not serviced. If these com man ds mu st be se rviced quick er, writ e data in sm aller bl ocks.
RELATED
BLOAD, POKE com mands
ERRORS
BAD ARGUMENT When any parameter is out of range or EPROM does not work properly.
HARDWAREWhen verify to EPROM is bad
EXAMPLE
The following example POKEs data into segment 1 of data RAM. The data is then saved to EPROM
segment 6 and loaded back to a different location in RAM. The data is then verified. A 128K RAM and
512K flash E PRO M m ust be in stalled for this e xample to w ork.
10 RA=512
20 FOR N=0 TO 1000 STEP 2
30 POKE W1,N,N
40 NEXT
50 FOR N=2000 TO 3000 STEP 2
60 POKE W1,N,0
70 NEXT
80 BSAVE6,RA,1,0,1000
90 BLOAD1,2000,6,RA,1002
100 FOR N=0 TO 1000 STEP 2
110 B=PEEKW(1,N+2000)
120 IF B<>N THEN PRINT "Error address",N," data is",B
130NEXT
2-7
Page 27
RPBASIC-52 PROGRAMMING GUIDE
CALL
Syntax:CALL address
Where: address = address of assembly language program from 0 to 65535
Function:Calls an assembly language program in external Progra m M emory
Mode:Command, Run
Use:CALL 16
Cards:All
DESCRIPTION
CALL instruction invokes an assembly language program. To return to Basic, you must execute a RET
instruction in the assembly language program. Original BASIC-52 code to multiply address by two and add
4100H was re mov ed.
Expressions and variables are not allowed for address; it must be an explicit number. The assembly language
program m ust reside in externa l program m emory. R PBA SIC-52 occ upies internal program memory
locations 0 through 6FFFH.
RELATED
none
EXAMPLE
CALL 0Performs soft power up reset
2-8
Page 28
RPBASIC-52 PROGRAMMING GUIDE
CARD$
Syntax:CARD $(expr)
Where: expr = 0 to 3, is the card reader to scan.
Function:Checks card reader for data. If present, returns the site code and card number. If no data is present,
an error code described below is returned. All data is return ed in a string form at.
Mode:Run
Use:$(0) = CARD$(N)
Cards:RPC-52, RPC-320, RPC -330
DESCRIPTION
CAR D$ returns eithe r the site code and card num ber or an error code . The site code a nd card num ber is
returned in the following format:
"SSS-NNNNN"
Site codes and card numbers have lead ing 0's. The '-' character is used a s a separator.
There are 4 different kinds of error returns possib le. The se erro rs are a lway s in a 2 c harac ter "-X" format.
'X' is a number with the following meanings:
1No card number present
2Hardware error - both data bits down
3Parity error
4Timeout error - some data received
A "-1" return is the most common. It indicates no card was swiped. A "-3" error indicates the card was
improperly swiped.
This comm and w as designed to work with Senso r Engi neerin g Co. (P hone 203 777 7444) m odel n o 3150 3.
Cards are in a 26 bit format: 2 check sum, 8 site code, 16 data.
Up to 4 card readers may be connected to the digital port at J3. Ports A and B are used to read and control the
readers. Port C m ay be used for ad ditional opto or digital I/O . Port A mus t be configured a s an input and po rt
B an output using the CONFIG LINE 100. . . statement. Port C may be input or output as required. The high
current driver, U12, must also be installed. Each card reader is connected to digital port J3 as follows:
Card NumberJ3 pins
HoldD1D0LED
0 8211910
1 625234
2 322241
3 718205
The green LED on the reader may be controlled using the LINE# command. A '0' forces the LED to green
and a '1' forces it to red. A yellow LED indicates a card has been swiped and the reader is ready to send the
information.
2-9
Page 29
RPBASIC-52 PROGRAMMING GUIDE
NOTE: This command takes approximately 27 ms to process. This is because the reader sends a bit of
information every 1 ms. Serial and timing interrup ts are processed a t the hardware level. How ever,
commands such as ONTICK and ONITR are delayed until CARD$ is finished processing the data.
RELATED
CONFIG LINE
ERROR
BAD ARGUMENT When expr > 3 or negative
EXAMPLE
The following example reads the card. CONFIG LIN E is performe d only once. T he error code is returne d in
B if no card was swiped.
CONFIG LINE 100,12,0,255,0,0
10 STRING 200,10
100 GOSUB 1000
110 IF B = 1 THEN 100
120 PRINT "Card number: ",$(0)
130 GOTO 100
1000 $(0) = CARD$(0)
1010 IF ASC($(0),1)= 45 THEN 1040:REM See if '-'
1020 B=0
1030 RETURN
1040 B = ASC($(0),2)-48:REM Return error number
1050 $(0)= ""
1060 RETURN
2-10
Page 30
RPBASIC-52 PROGRAMMING GUIDE
CBY
Syntax:CBY(expr)
Where: expr = address from 0 to 65535
Function:Reads internal program code
Mode:Command, run
Use:PRINT CBY(1000H)
Cards:All
DESCRIPTION
The C BY instruc tion rea ds data from p rogram mem ory spa ce in the 8052. expr must evaluate to a valid
integer address of 00H through 0FFFFH (65535). Code memory is read-only.
RELATED
DBY, XBY, PEEK, POKE
ERROR
BAD ARGUMENT expr must be a valid integer (0 through 65535).
EXAMPLE
10 FOR N=0 TO 10
20 PRINT CBY(N),
30 NEXT
>RUN
97 203 255 210 22 50 2 39 110 255 255
2-11
Page 31
RPBASIC-52 PROGRAMMING GUIDE
CHR
Syntax:CHR(expr)
CHR(string, positi on)
Where: expr = number from 0 to 255
string = string variable
position = 1 to length of string
Function:Converts expr to ASCII character or prints string at position
Mode:Command, run
Use:PRINT CHR (65)
PRINT CH R($(0),1)
Cards:All
DESCRIPTION
CHR is a dual use ope rator, similar to AS C. One ve rsion converts a nu meric exp ression to an A SCII
character, allowing a variety of string manipulation operations. The second version uses CHR to print
individual ch aracte rs in an A SCII s tring. expr is a decimal number and truncates numbers from 0 through
65535. There must be no s pace betw een C HR and the left pa renthe ses or a n AR RAY SIZ E erro r results .
Although expr can be any integer, printable ASCII characters range from 20H through 7E H (32 through 127).
The STR function may be used to m anipulate and print longer portions of strings.
RELATED
ASC, STR, STRING
ERRORS
BAD ARGUMENT expr can't be truncated to an integer (0 through 65535)
ARRAY SIZEspace between CHR and left parentheses
EXAMPLE
10 STRING 200,20
20 $(1)="1234567890"
30 FOR N=64 TO 80
40 PRINT CHR(N),
50 NEXT
60 PRINT
70 FOR N=1 TO 9
80 PRINT CHR($(1),N),
90 NEXT
RUN
@ABCDEFGHIJKLMNOP
1234567890
2-12
Page 32
RPBASIC-52 PROGRAMMING GUIDE
CLEAR
CLEAR S
Syntax:CLEAR
CLEAR S
Function:Sets variables to zero, clears stacks
Mode:Command, run
Use:CLEAR
CLEAR S
Cards:All
DESCRIPTION
The CLEAR instruction sets all variables to 0 and resets all Basic stacks. ONERR is cleared. Error trapping
must be redeclared after a CLEAR. CLEAR is generally used to clear all variables. CLEAR does not deallocate me mory alloca ted to st rings by the ST RIN G inst ruction . It does clear the conte nts of th e string s.
Data put to the stack by PUSH is cleared. CLEA R also resets an y FOR -NEXT loops. A C -STAC K error is
returned when a NEXT is performed after a CLEAR . CLEAR also resets any GOSU B return addresses.
Use CLEAR to perform a soft reset of a program. Keep in mind that multi-tasking routines are not cleared or
reset using this command. However, if CLEAR is used as part of a multi-tasking program (ON COM$, ON
LINE, etc.), a RETURN w ill cause a C-S TAC K error.
CLEAR S resets the control stack (C-STA CK) only . This stack is used in loops and subrou tines to tell it
where to return to. Use this command to branch (GOTO) out of FOR-NEXT, GOSUB-RETURN, DOUNTIL type structures. It can be used in emergency stop situations where nesting of loop structures is not
known. Variables are not cleared using CLEAR S.
RELATED none
EXAMPLE
10 CLEAR TICK(0)
20 ONTICK 1,1000
25 ONERR 500
30 IF TICK(0)<2.5 THEN 30
40 A=TICK(0)/0
50 IF TICK(0) < 3.3 THEN 50
60 CLEAR
70 PRINT "CLEARED"
80 GOTO 80
500 PRINT "IN ERROR"
510 ONERR 500
520 GOTO 50
1000 PRINT TICK(0),A
1010 A=A+1
1020 RETI
>RUN
1 0
2 1
IN ERROR
3 2
4 0
5 1
6 2
2-13
Page 33
RPBASIC-52 PROGRAMMING GUIDE
The above e xam ple sho ws tha t ONTIC K con tinues to run a fter a C LEA R sta teme nt but v ariable s are cleared.
If a program error were generated after the clear, the program would stop because ONERR was cleared.
The next example demonstrates how CLEAR S can be used in a FO R-NE XT loop . A C-ST ACK error is
returned if the CLEAR S is not in line 20.
10 FOR N=0 TO 10
20 IF N=5 THEN CLEAR S : GOTO 10
30 PRINT N
40 NEXT
>RUN
1
2
3
4
0
1
2-14
Page 34
RPBASIC-52 PROGRAMMING GUIDE
CLEAR COM
Syntax:CLEAR COM(port)
Where: port = 0 or 1 , the seri al com munication port. port may be larger. Check your cards manual.
Function:Clears received characters in specified serial port buffer.
Mode:Run
Use:CLEAR COM (0)
Cards:All
DESCRIPTION
Received characters in the specified serial port are cleared. Characters in the transmit buffer are not affected.
RELATED
COM, COM$, GET
ERRORS
BAD SYNTAXAny parameters left out
BAD ARGUMENT When port > 1 or card limit or negative
EXAMPLE
100 CLEAR COM(1)
2-15
Page 35
RPBASIC-52 PROGRAMMING GUIDE
CLEAR DISPLAY
Syntax: CLEAR DISPLAYClears character and, if available, graphics displays.
CLEAR DISPLAY LINE Clears character line
CLEAR DISPLAY LINE(x1,y1)-(x2,y2)Clears graphics line
CLEAR DISPLAY P(x,y)Clears a point on a graphics screen
CLEAR DISPLAY CClears characters only on graphics screen
CLEAR DISPLAY GClears graphics only on graphics screen
Function:Clears display as directed by its options
Mode:Command, Run
Use:CLEAR DISPLAYClears entire display and homes cursor
Cards:All
DESCRIPTION
Character displays may use only CLEAR DISPLAY and CLEAR DISPLAY LINE.
Character displays require several milli-seconds to clear. After CL EAR DISPL AY state ment, it is best to
execute several other RPBASIC-52 commands before using the DISPLAY command again. This will allow
the display to "catch up" to the program. Failure to do so may result in an incomplete screen clear or missing
characters/data.
NOTE: CLEAR DISPLAY LINE requires several milli-seconds to execute. LCD displays require up to 10
ms while the VF display requires 20 ms. Processing other RPBASIC-52 interrupts are delayed by
this amount of time.
The x and y graphic coordinates are the same as those specified in the DISPLAY LINE and DISPLAY P
commands.
RELATED
DISPLAY
ERROR
BAD SYNTAXWhen wrong option is used with a display.
2-16
Page 36
RPBASIC-52 PROGRAMMING GUIDE
CLEAR TICK
CLEAR KEYPAD
Syntax:CLEAR TICK(timer)
Where: timer = 0 to 3
CLEAR KEYPAD
Function:Resets specified tick timer or clears keypad buffer.
Mode:Command, Run
Use:CLEAR TICK(1)
DIFFERENCES FRO M BASIC-52
The TICK function replaced TIME as a process clock. See TICK function for more information. KEYPAD
has no equivalent function in BASIC-52.
DESCRIPTION
There are four independent tick timers that can be cleared independently of each other. This statement resets
any one of the four tick timers to 0.
CLEAR K EYPA D clears the k eypad buffer.
RELATED
TICK, KEYPAD
ERRORS
BAD SYNTAXAny parameters left out
BAD ARGUMENT When timer > 3 or negative
2-17
Page 37
RPBASIC-52 PROGRAMMING GUIDE
COM
Syntax:COM(port)
Where: port = 0 or 1 , the seri al com munication port. port may be larger. Check your hardware
manual.
Function:Returns the number of characters received in the specified serial port buffer.
Mode:Run
Use:A = COM (0)
Cards:All
DESCRIPTION
Use this function in conjunction with GET and COM $ to determine the number of characters to extract from
the serial buffer. A GET 0 data value can be processed with the knowledge that it is a valid character and not
an indication of an empty buffer.
RELATED
COM$, GET
ERRORS
BAD SYNTAXAny parameters left out
BAD ARGUMENT When port > 1 or card limit or negative
2-18
Page 38
RPBASIC-52 PROGRAMMING GUIDE
COM$
Syntax:$(n) = COM$(port)
Where: port = 0 or 1 , the seri al com munication port. port may be larger. Check your hardware
manual.
Function:Return either all characters or up to a <CR> in specified serial port.
Mode:Run
Use:$(0) = COM$(0)
Cards:All
DESCRIPTION
Characters in the specified com municatio ns port buffer are put into the string (on the left side of the = ) until
one of three conditions occur: 1) There are no more characters to e xtract. 2) A <C R> cha racter is
encountered. 3) The maximum number of characters specified in the STRING statement is reached.
This statement is useful when the application cannot risk using an INPUT statement. The INPUT statement
waits until a <CR> is returned before continuing execution.
Unlike the INPUT sta tement, the va lue of all characters, ex cept a <C R> (AS CII 0DH ) are returned. All
control characters and characters with ASCII values above 128 are returned.
NOTE: COM$ works only when it is assigning another string variable. A BAD SYNT AX error is returned
when it is part of a PRINT, IF-THEN, ASC, or other command or function. Use this function only as
shown in SYNTAX above.
RELATED
GET, INPUT, ON COM$
ERRORS
BAD SYNTAXAny parameters left out
BAD ARGUMENT When port > 1 or card limit or negative
EXAMPLE
The following example prints the num ber of characters in th e buffer as they are e ntered. Wh en 10 charac ters
have been received, the string is printed.
10 STRING 100,20 : CLEAR COM(0)
15 PRINT "Enter characters."
20 A=COM(0)
30 B=COM(0)
40 IF A=B THEN 30
50 PRINT "Number of characters in buffer:",B, CR ,
55 A=B
60 IF B<10 THEN 30
70 $(0)=COM$(0)
75 PRINT
80 PRINT "Received string =",$(0)
100 PRINT "Characters left in buffer=",COM(0)
110 GOTO 20
When you enter a <C R> before the 10th charac ter, the string to the <C R> is returned . Note that there are still
some characters left in the buffer. W hen 10 chara cters are entered w ithout a <CR >, characters are put into
the string until th e buffe r is em ptied o r the m axim um n umb er of strin g char acters set by S TRING is reac hed.
To see how this works, chang e line 60 to IF B <25 TH EN 30. T he number of characters left in the buffer will
always be 5, unless a <CR> was entered.
2-19
Page 39
RPBASIC-52 PROGRAMMING GUIDE
CONT
Syntax:CONT
Function:Continue program execution after a STOP or Comm and-C
Mode:Comm and
Use:CONT
Cards:All
DESCRI PTIO N
CONT resum es program execution follow ing a <Ctrl-C > or STO P instruction. You can display or m odify
variables while the program is stopped, but you cannot continue a program that is modified.
RELATED
STOP, GOTO, RUN
ERROR
CAN'T CONTINUE When program was m odified.
2-20
Page 40
RPBASIC-52 PROGRAMMING GUIDE
COS
Syntax:COS(expr)
Where: expr = numeric value up to ±200,000
Function:Returns the trigonometric cosine of expr which is in radians.
Mode:Command, run
Use:PRINT COS (PI)
Cards:All
DESCRIPTION
SIN, COS, and TAN operators use a Taylor series to calculate the function. These operators first reduce the
argument to a value that is between 0 and PI/2. the algorithm used to reduce the value will reduce accuracy
when value is large. To maintain accuracy, keep the arguments for trig functions as small as possible.
ERROR
ARITH. UNDERFLOW value or result is less than RPBASIC-52's smallest floating-point value of ±1E-127
ARITH. OVERFLOWvalue or result is greater than RPBASIC-52's largest floating-point value of
±.9999999E+127
DIVIDE BY ZEROAttempt to take TAN(X) when COS(PI/2) = 0
Syntax:PRINT CR,
Function:Used with P RIN T. Sen ds a ca rriage r eturn w ithout a line fee d.
Mode:Command, run
Use:PRINT CR,
Cards:All
DESCRIPTION
Used to update a line on a serial console device. A comma is necessary to prevent the usual line feed from
terminating the PRINT instruction.
RELATED
PRINT
EXAMPLE
100 PRINT TICK(0),CR,
110 GOTO 10
>run
3.242
The number is continuously printed at the same position.
2-22
Page 42
RPBASIC-52 PROGRAMMING GUIDE
COUNT (statement)
Syntax:COUNT counter ,data
Where: counter = 0 or 1
data = 0 to 16777215
Function:Writes data to spec ified up /dow n coun ter.
Mode:Command, Run
Use:CO UN T 0,A
Cards:RPC-320, RPC-330
DESCRIPTION
Use this command to write 3 data bytes to the preset register (PR) in the LSI 7166 counter. This command
does not transfer PR to the counter (CNTR). To do this, execute:
LINEB 6,X,8
Where: X = 1 for counter 0, 3 for counter 1.
NOTE: The sign of data is ignored. It can be a positive or nega tive nu mbe r. Wh en neg ative, data is simply
treated as a positive num ber.
Decimal portion of data is ignored. For exam ple, if data = 100.99999, 100 is loaded into the counter.
See your hardware manual for more information about using the LSI 7166 chip.
Software counters 4 - 11 cannot be set.
RELATED
COUNT (function)
ERROR
BAD ARGUMENTWhen counter <> 0 or data out of range.
EXAMPLE
10 COUNT 0,124735
2-23
Page 43
RPBASIC-52 PROGRAMMING GUIDE
COUNT (function)
Syntax:A = COUNT(counter)
Where: counter = 0 - 1, or 4 - 11
Function:Reads a multimode hardware or software counter
Mode:Command, Run
Use:A = COU NT(0)
Cards:RPC-320, RPC-330
DESCRIPTION
RPBASIC-52 recognizes a hardware and software counter. The hardware counter is 24 bits wide from a LSI
7166 chip. (Your board may use a different kind. Please check your hardware manual.) The RPC-320 has
one of these and the RPC-330 has two. Additionally, there are 8 software counters on all cards.
counter 0 and 1 retrieve a 24 bit (3 byte) number from the LSI 7166 multimode counter IC. A number from 0
to 16777215 is returned. See your hardware manual for more information about using the LSI 7166 chip.
Eight software counters, set by the ON COUNT comm and, return a count from 0 to 65535. Software counter
is 4 to 11. A software count is incremented when a line goes low.
RELATED
COUNT (statement), ON COUNT
ERROR
BAD ARGUMENT When counter is out of range
EXAMPLE
The following example sets up line 3 as a software counter input. A count is printed once a second. A count
is incremented by bringin g line 3 low m omentarily.
ON COUNT can be configured to generate an interrupt when a specified number of counts is reached. See
COUNT MULTITASKING under MULTITA SKING CONSTRU CTS a t the beginning of this m anual.
2-24
Page 44
RPBASIC-52 PROGRAMMING GUIDE
DATA
Syntax:DATA expr [,expr,...]
Where: expr = numeric data.
Function:It is an expression list used by READ.
Mode:Run
Use:DATA 23.4,17,3.2,PI*3
Cards:All
DESCRIPTION
Elements of a DATA statement are sequentially retrieved by the READ instruction. Multiple DATA
expressions on a single program line must be separated by commas. There must be no spaces between expr
and the commas.
See RESTORE for more information and exam ples.
RELATED
READ, RESTORE
2-25
Page 45
RPBASIC-52 PROGRAMMING GUIDE
DATE (function)
Syntax:A = DATE(n)
Where: n = 0 to 3
0 = year (last two digits)
1 = month
2 = day
3 = day of week
Function:Returns the month, day, day of week, or year from the optional real time clock
Mode:Command, Run
Use:A=D ATE (2) Returns day of month
Cards:All. Note exceptions for RPC-52.
DESCRIPTION
A DS1216DM must be in the RAM socket. Consult your hardware manual for location. A numerical value
of the month, day, or year is returned. The program under the TIME function is used to convert numerical
date to a string. Substitute DATE for TIME in the program. STR function 10 also converts a number to a
string.
A HARDWARE error is returned if the RTC is missing or bad. Use the ONERR construct to trap a defective
DS1216DM. Hardware error code at address 101H is 50.
Day of week is returned only on cards w hich use a DS1216DM clock module. (This excludes t he RPC-5 2.)
RELATED
DATE (command), TIME
ERRORS
BAD ARGUMENT When n out of range or negative
HARDWARERTC module missing or bad
EXAMPLE
100 PRINT "Time: ",
110 FOR N=0 TO 2
120PRINT TIME(N),
130 NEXT
140 PRINT " Date: ",
150 FOR N=0 TO 3
160 PRINT DATE(N),
170NEXT
180PRINT CR,
190GOTO 100
run
Time: 13 24 12 Date: 94 11 14 3
2-26
Page 46
RPBASIC-52 PROGRAMMING GUIDE
DATE (statement)
Syntax:DATE year,month,day[,day of week]
Where: year = 0 to 99
month = 1 to 12
day = 1 to 31
day of week = 1 to 7
Function:Sets the date to the real time clock
Mode:Command, Run
Use:DATE 96,11,17Sets date to November 17, 1996
Cards:All
DESCRIPTION
Leap year is automatically set. Tests for day check limits of 1 to 31. It does not check for a valid day in a
month. You could set 2-31-96 as a valid date.
This command m ust be execute d first to turn on the clock m odule. DATE and T IME functions or the TIM E
command will not work otherwise.
day of week can only be set on ca rds usin g a DS 1216D M type clock module. (This exc ludes t he R PC-5 2.)
RELATED
DATE (function), TIM E
ERRORS
BAD ARGUMENT When month, day, or year is out of range.
HARDWAREClock module missing or bad.
2-27
Page 47
RPBASIC-52 PROGRAMMING GUIDE
DBY
Syntax:A=DBY(expr)DBY(expr)=variable
Where: expr = 0 to 255
variable = 0 to 255
Function:Read/write internal data memory.
Mode:Command, run
Use:DBY(0F0H ) = 45H
A=DBY(100)
Cards:All
DESCRIPTION
The D BY instruc tion ret rieves or assig ns a value to the 8052 interna l data m emory. expr and variable must
both must be between 0 and 255 since there are only 256 internal memory locations and one byte can only be
between 0 and 255.
RPBASIC-52 uses many internal memory locations for its own use. Change internal memory with caution or
Basic may malfunction. Locations 1BH through 21H may be used in any way you wish.
RELATED
CBY, XBY
ERROR
BAD ARGUMENT Invalid expr value, such as DBY(256) or attempt to assign an invalid value to a
DBY(expr), such as DBY(18H)=1000.
EXAMPLE
100 DBY(1EH) = 234
110 PRINT DBY(1EH)
>run
234
2-28
Page 48
RPBASIC-52 PROGRAMMING GUIDE
DIM
Syntax:DIM name(size)[, name(size)...]
Where: name = Any valid variable name
size = 1 to 255 elem ents
Function:Reserves storage for single-dimension array.
Mode:Command, run
Use:DIM FLOW(200) : REM dimensions a 200 element array called FLOW
Cards:All
DESCRIPTION
The maxim um num ber of array elements is 255, accessed as name(0) through name(254). CLEAR, NEW , or
RUN com man ds de-allocate all array storage. T he def ault siz e of und eclare d arrays is 10 (i.e . 11 elem ents).
An array cannot be redimensioned after it has been dimensioned. Memory required for an array is ((integer
size + 1) * 6). Array A(99) requires 600 bytes of memory. Available memory typically limits the size and
number of dimensioned arrays.
RELATED
STRING, CLEAR
ERROR
ARRAY SIZE When size >255
EXAMPLE
10 DIM FLOW(200), LEVEL(200)
20 ONTICK 1,1000
30 IF PTR < 200 THEN 30
40 ONTICK 0,1000
50 FOR N=0 TO 199
60 PRINT FLOW(N),LEVEL(N)
70 NEXT
80 END
1000 FLOW(PTR)=AIN(0)
1010 LEVEL(PTR)=AIN(1)
1020 PTR=PTR+1
1030 RETI
2-29
Page 49
RPBASIC-52 PROGRAMMING GUIDE
DISPLAY
Syntax:DISPLAY option[,option][,option]
Where: option is one or more of the following
"string"Prints to display
$(n)Prints to display
(row,col[,cursor])Positions cursor and turns it on or off
dataPuts data values to display
CRPrints a carriage return to the display
LINEPuts a line to a graphics display
PPuts a point to a graphics display
ON [G,C]Enables character, graphic, or both displays
OFF [G,C]Turns off character, graphic, or both displays
Function:Writes information to display.
Mode:Command, Run
Use:DISPLAY (1,2,OFF),28,"Name: ",$(0)
Cards:All
DESCRIPTION
DISPLAY has many options, some of which cannot be used with all displays. Graphics commands (LINE, P,
C, and G) are only valid with the LCD -5003. An error is returne d when the y are used w ith character only
displays.
Strings and cursor positioning may be placed in any order on the comm and line with the exception of data.
The following example shows how some options can be combined in a program line.
100 DISPLAY (1,0,ON),"Batch no.: ",$(0),(2,0),"Enter process no.:"
The cursor is positioned at line 1, first position (0) and the cursor is turned on. The string "Batch no.: " is
printed. The string in $(0) is then printed. The cursor is then re-positioned to line 2 (third line down), first
position. The string "E nter process no.:" is then printed. The curso r is positioned just after the ':' characte r.
DISPLAY does not format text like PRINT. SPC, TAB, and USING commands return an error. Use STR
function 10 to format numbers.
NOTE: Unlik e the P RIN T com man d and s erial po rts, DIS PLA Y doe s not buffer sending data to th e displ ay.
Due to display speed lim itation s, it ma y take up to 1 m s to write 1 ch aracte r or data point to a scree n.
Long strings or lines may take several milli-seconds. Time sensitive interrupts, such as ONTICK,
can be "missed" if printing is long an d the tick interval is very short. In these situations, it is best to
break up any DISPLAY com mand into smaller sizes.
The following paragraphs explain each display option.
"string" is any quoted text used in PRINT statements.
DISPLAY "Hello world"
$(n) is any string array. Variable numbers must be printed from this array. The program in TIME function
shows how to convert a number into a string.
DISPLAY $(0)
2-30
Page 50
RPBASIC-52 PROGRAMMING GUIDE
(row,col,[,cursor]) positions the cursor and, optionally, turns it ON or OFF. This option affects the character
cursor position only. The row and collum alw ays start at 0,0, which is the upper left corner o f the screen. If
row or col exceed the displays limits, a B AD A RGU MEN T error is returned. Th e optional cursor is turned
on or off using ON or OFF.
DISPLAY (1,5)
DISPLAY (2,0,OFF)
data is byte information written to the display. Functionally, it is equivalent to CHR$(n) found in other
Basics. data can be used to control additional features of a display not normally available. For example, the
vacuum florescent display brig htness can be dimm ed to minimum by exec uting D ISPL AY 28.
NOTE:data does not update cursor position. The display may act 'unusual' when printing characters or
strings. The best way to solve this problem is to position the cursor before resuming string displaying.
NOTE:data should not be used with the graphics display. Character values are offset by 20H. For example,
the ASCII v alue fo r 'A' is 41H . The so ftware subtra cts 20H from this num ber before se nding it to the d isplay.
CR simply positions the cursor at the beginning of the current line.
DISPLAY CR
The following options are valid on the LCD5003 display only.
LINE draws a line on a graphics display. Its syntax is:
DISPLAY LINE (x1,y1)-(x2,y2)
Where: x1,x2 = 0 to 159
y1,y2 = 0 to 127
The L INE option is optim ized for high sp eed. H owe ver, ne arly ve rtical lin es will take m uch lo nger to draw .
A line is erased using the CLEAR DISPLAY LINE (x1,y1)-(x2,y2) command.
P puts a single point to a graphics display. Its syntax is:
DISPLAY P(x,y)
Where: x = 0 to 159
y = 0 to 127
These values are valid for LCD5003 display only.
A line is erased using the CLEAR DISPLAY P(x,y) command.
ON enables character, graphics, or both displays. Three syntaxes possible are:
DISPLAY ONTurns on both character and graphics displays.
DISPLAY ON GTurns on graphic display only.
DISPLAY ON C Turns on character display only.
Power on default is both graphics and character display ON. Turning on character or graphic does not affect
the other. In other words, you could turn the character display ON and OFF without affecting the graphics
display.
OFF disables character, graphics or both displays. Three syntaxes possible are:
2-31
Page 51
RPBASIC-52 PROGRAMMING GUIDE
DISPLAY OFFTurns off both character and graphics displays.
DISPLAY OFF GTurns off graphic display only.
DISPLAY OFF CTurns off character display only.
Turning off the character display does not turn off graphics.
Using DISPLAY ON /OFF [option ] allows you to sw itch betwee n character and graphics displays. It is
possible to update both graphics and character screens even if they are off.
RELATED
CONFIG DISPLAY
ERROR
BAD SYNTAXWhen option is invalid
2-32
Page 52
RPBASIC-52 PROGRAMMING GUIDE
DO-UNTIL
Syntax:DO
{program statements}
UNTIL relational expr
Where: relational expr is any logical evaluation such as =, <, >, etc.
Function:Executes a number of program statements a relational expression is true.
Mode:Run
Use:100 A=0 : DO : A=A+1 : PRINT A : UNT IL A=4 : PRINT "Done"
Cards:All
DESCRIPTION
This statement always executes at least once. DO-UNTIL loops may be nested. This loop may be exited
without meeting relational expr by executing a CLE AR or C LEA R S statem ent.
This statement always executes to UNTIL once. When relational expr is evaluated and if it is false, program
flow branches bac k to D O. If true , progra m res ume s at the next sta teme nt after UN TIL.
When there are no {program statem ents} betw een DO and UN TIL, and {relational expr} is false, the "loop"
will repeat forever, or until a <ctrl-c> is typed at the console.
DO-UNTIL and DO-WH ILE loops can be nested.
RELATED
DO-WHILE, FOR-TO-NEXT-STEP
ERROR
BAD SYNTAX When relational expr is omitted
EXAMPLE
The following program stays in a DO-UNTIL loop until a line has changed.
10 ON LINE 0,0,500
20 DO
30 UNTIL C=1
40 PRINT "Line 0 changed. Is now a",line(0)
50 C=0
60 GOTO 20
500 C=1
510 RETURN
>run
Line 0 changed. Is now a 0
Line 0 changed. Is now a 1
Line 0 changed. Is now a 0
2-33
Page 53
RPBASIC-52 PROGRAMMING GUIDE
DO-WHILE
Syntax:DO
{program statements}
WHILE {relational expr}
Function:Executes {program statements} w hile {relational expr} is true.
Mode:Run
Use:100 CLEAR TICK(0) : DO : PRINT TICK(0) : WHILE TICK(0)<10
Cards:All
DESCRIPTION
The {program statem ents} betw een DO and W HILE a re executed o nce, regardless of the {relational expr}
result. At WH ILE the {re lational expr} is evaluated. If true, all {program statements} are executed again,
and the test is repeated. If false, execution continues at the program statement after WHILE. DO-WHILE
and DO-UNTIL loops can be nested.
RELATED
DO-UNTIL, FOR-TO-STEP-NEXT
EXAMPLE
The following program stays in a DO-UNTIL loop until a line has changed.
10 ON LINE 0,0,500
20 DO
30 WHILE C=0
40 PRINT "Line 0 changed. Is now a",line(0)
50 C=0
60 GOTO 20
500 C=1
510 RETURN
>run
Line 0 changed. Is now a 0
Line 0 changed. Is now a 1
Line 0 changed. Is now a 0
2-34
Page 54
RPBASIC-52 PROGRAMMING GUIDE
END
Syntax:END
Function:Terminates program execution and returns to command mode.
Mode:Run
Use:65000 END
Cards:All
DESCRIPTION
The EN D instruction term inates Basic program ex ecution. If no EN D instruction is used at the end of a
program, the last instruction automatically terminates the program. Use END after the body of your program
and prior to any subroutines.
Without an END after the main body of your B asic program and prior to any subroutine program lines,
RPBASIC-52 will attempt to execute any subroutines at the end of your program as if they were a
continuation of the main program. This will generate a C-STAC K error whe never a RE TUR N is
encountered.
RELATED
CONT, STOP, GOSUB, ON-GOSUB
ERROR
CAN'T CONTINUE The CON T instruction cannot follow an END instruction.
EXAMPLE
10 GOSUB 100
20 END
100 PRINT PI
110 RETURN
>run
3.1415926
If you remove line 20, a C-Stack error is returned.
2-35
Page 55
RPBASIC-52 PROGRAMMING GUIDE
EXECUTE
Syntax:EXECUTE [segme nt]
Where: segment = program to execute
Function:Loads and runs program specified by segment.
Mode:COMMAND, RUN
Use:EXECUTE n
Cards:RPC-320, RPC-330
DESCRIPTION
Com man d gets a progra m from the flas h EPR OM and executes it. segment species the program to exe cute.
The program saved by the S AVE n comm and is executed. The range o f segment depends upon the flash
EPROM size. See the SAVE comm and for more information.
The effect of EXEC UTE is the same a s typing LO AD n, then RUN . The difference is E XECUTE is part of a
program.
NOTE: Every time EX ECUT E is run, all variables and strings are reset. Variables and strings CANNOT be
passed from one program to another except through peeking and poking to RAM. ONTICK and
ONITR interrupts are cleared as is ONERR.
String and numeric data can be saved for use by other programs using any of the POKE and PEEK
statements. Data can be POKE d in to space ab ove MT OP (7E0 0H in a 32K RAM system) or into memory
segment 1 (128K RAM) or 1-7 (512K R AM).
Some parameters are not cleared by running EXECUTE. These are the tick timers (TICK), serial
communication buffers, and data saved by POKEing. No hardware conditions are reset. No parameters set
by any CO NFIG sta tement are reset.
Loading and executing time depend upon program length. 0.22 seconds is required for clearing variables and
resetting Basic. Ad d to this time the ac tual tra nsfer tim e. Transfer tim e is at a rate of 5 0,000 b ytes/se cond.
A 20K program requires about 0.4 seconds to begin running after the EXECU TE statement is finished.
RELATED
LOAD, SAVE
ERROR
BAD ARGUM ENT when segment is out of range.
EXAMPLE
The first lines were saved to program segment 0. The second set to 1.
10 PRINT "Program number 0"
20 EXECUTE 1
>save 0
10 PRINT "Program number 1"
20 EXECUTE 0
>save 1
>run
Program number 0
Program number 1
Program number 0
2-36
Page 56
RPBASIC-52 PROGRAMMING GUIDE
EXP
Syntax:EXP(expr)
Function:Raises "e" (2.71828) to the power of expr
Mode:Command, run
Use:PRINT EXP(C OS(1))
Cards:All
DESCRIPTION
This function returns the result of the num ber Q (2.718282) raised to the power given by expr. This function is
very computation time intensive. Small values of expr take about 5 milli-seconds to calculate while larger
ones (near 250) require nearly 0.2 seconds. Avoid using this function in tight control or time intensive
applications.
ERROR
BAD ARGUMENT When result of expr > 256
2-37
Page 57
RPBASIC-52 PROGRAMMING GUIDE
FOR-TO-STEP-NEXT
Syntax:FOR variable= initial index expr TO index limit expr [STEP step expr ]
progra m statem ents
NEXT [variable]
Where: variable = any valid variable symbol
initial index expr = starting value assigned to variable
index limit expr = ending va lue of variable
step expr = optional increment or decrement to variable when repeating a loop
Function:Looping structure useful for executing a sequence of instructions a number of times.
Mode:Run, command
Use:FOR A=0 to 4000 STEP 200 : AOT 0,A : NEXT
Cards:All
DESCRIPTION
The FOR-TO -STEP -NEX T instruction is a loop structure com mon to m any high leve l languages. It is used to
perform progra m statem ents a number of tim es.
variable is a loop counter initialized to initial index expr at the start of the loop. A number of program
statemen ts are executed until NEX T is encoun tered. At this point the v alue of step expr is added to the value
of variable . The resulting new variable value is compared to the value of index limit expr. If the new value
of variable value is less than or equal to the value of index limit expr, all program statements are executed
again, and the test is re peate d.
progra m statem ents are always e xecuted at lea st once. If step expr is larger than index limit expr, the loop
executes only once.
STEP is optional. When omitted, it defaults to 1. The value of step expr may be positive or negative.
FOR -NE XT l oops m ay be inside o ther FO R-NEXT loops. variable following N EXT is optional.
There are two ways to break out of a for next loop and still maintain the control stack . The first is to execute
a CLEAR S command. This command also clears any subroutine return locations and DO-WHILE, DOUNTIL loops. Another is to set variable to a high value within program statements. When a program
continuously breaks out of a FO R-NE XT loop and re-declares a new loop, a C -Stack error is even tually
returned.
RELATED
DO-UNTIL, DO-WHILE
ERROR
C-STACK NEXT without a corresponding FOR. This error can also appear if a number of FOR-NEXT
loops were set up but were illegally branched out of or re-declared.
2-38
Page 58
RPBASIC-52 PROGRAMMING GUIDE
EXAMPLE
The following example gets characters from the receive buffer and generates a checksum. A string of 10
characters is entered at com port 0.
10 STRING 200,20
20 PRINT "Type in 10 characters. Characters are not echoed"
30 IF COM(0) < 10 THEN 30
40 $(0) = com$(0)
50 CKSUM = 0
60 FOR N = 1 to STR(0,$(0))
70 CKSUM = CKSUM + ASC($(0),N)
80 NEXT
90 PRINT "Checksum of incoming string:",CKSUM
>run
Type in 10 characters. Characters are not echoed
(1234567890 are entered at the keyboard)
Checksum of incoming string: 525
2-39
Page 59
RPBASIC-52 PROGRAMMING GUIDE
FREE
Syntax:FREE
Function:Returns the bytes of available in program RAM
Mode:Command, run
Use:PRINT FREE
Cards:All
DESCRIPTION
FREE returns how m any bytes of R AM are available to the program and Basic variables. It does not return
the amount of expanded RAM in 128K or 512K RAM systems. The amount of free memory is determined by
the following formula:
FREE = MT OP - LE N - system mem ory
"system memory" on cards with two serial ports is 1791. Add 512 bytes for any additional serial ports on a
card.
RELATED
LEN
ERROR
BAD SYNTAX Attempt to assign a value to FREE
2-40
Page 60
RPBASIC-52 PROGRAMMING GUIDE
FREQ (Function)
Syntax:FREQ(channel)
Where: channel = 0 or 1, depending upon card.
Function:Returns a counter value
Mode:Command, run
Use:PRINT FR EQ(0)
Cards:RPC-210, RPC-320, RPC-330 (RPC-210 and -320 are channel 0 only)
DESCRIPTION
This command returns a frequency, or number of pulses over a period of time. FREQ returns the latest value
from the hardware counter. FREQ does not actually read from the counter. The operating system reads the
counter at set intervals defined by CONFIG FRE Q and stores th em for retrieval by this function. This
function is used to read analog input modules made by Greyhill, Dutec, and others. Equivalent 15+ bit analog
input readings are theoretically possible.
FREQ function returns 0 until set up by CONFIG FREQ.
The latest FR EQ valu e remains in mem ory until updated b y the RPB ASIC-52 operating system . The update
interval is dete rmine d by the CONFIG FRE Q com man d.
Avoid using COUNT(n) when using this command. It is possible values returned by COUNT(n) could be
wrong.
Hardware counters (LSI 7166) are used to count pulses. CONFIG FREQ defines the time interval between
readings. The operating system reads and resets the counters every time interval. Thus, you can measure a
frequency in 1/10 second. The result is multiplied by 10 to obtain the "true" frequency. Errors in this case
are also multiplied by 10. The best rule is to set the time interval in CONFIG FREQ for as long of a period as
possible (up to 1.275 seconds) to get the most stable and accurate readings. Shorter intervals make counts
appear less stable.
Best resolution is below 80 Khz at a measurement interval of 1/2 second. Between 80 Khz and about 190
Khz counts can easily vary by ±2. From 190 Khz to about 1 Mhz, counts vary by up to ±10. Above 1 Mhz,
counts vary much more. Counting to 20 Mhz is possible.
You will have to play with the m easure men t interv al, base d on the input frequenc y and d esired stabilit y.
Averaging the counts helps stabilize the readings.
There are several sources of errors and instability. The time interval between counter readings is based on the
system tick tim er, which is base d on the crystal. Ac curacy is usually better than 0.01% . The error is very
noticeable at higher (> 200Khz) frequencies. Another potential source of error is the program or functions
you may be executing. Some functions, such as AIN, turn off all interrupts for a "short" period of time (50
micro-seconds). What this means is, if it is time for the operating system to read the counters, the reading
will be delayed by up to 50 micro-seconds. If the frequency is very high, additional counts are read. No
counts are missed, so averaging readings helps to reduce errors.
Counts are missed when the frequency is above 1 Mhz (500 Khz on the RPC-210). This is because of CPU
processing time between latching and reseting the counter (about 1 - 2 micro-seconds). Increasing the time
interval between readings helps to reduce errors but does not eliminate them.
RELATED
CONFIG FREQ
ERROR
2-41
Page 61
RPBASIC-52 PROGRAMMING GUIDE
BAD DATAWhen channel is out of range for a card.
EXAMPLE
The following example sets up frequency multitaskin g and prints the counts received in a time interval.
10 LINEB 6,1,32
20 LINEB 6,1,72 : REM Reset counter and enable inputs
30 CONFIG FREQ 0,200 : REM Get count every second (5 ms * 200)
40 C = 5/56000 : REM Constant using Greyhill module. 5V / 56000Hz = V/Hz
50 CLEAR TICK(0)
60 IF TICK(0) < 1 THEN 40 : REM Wait for a second
70 A = FREQ(0) : REM Get frequency
80 V = (A-14400) * C : REM Multiply by constant to get Voltage
90 PRINT "Voltage = ",V, "Frequency =",A
100 GOTO 50
You may need to add a 1K ohm pull up resistor from the output of the Greyhill module to the input of the
counter. The input rise time should be 1 micro-second or faster.
2-42
Page 62
RPBASIC-52 PROGRAMMING GUIDE
GET
Syntax:A = GET
Function:Gets character from buffer.
Mode:Run
Use:A = GET
Cards:All
DESCRIPTION
GET is similar to INKEY$ in other Basic languages. GET returns the ASCII value of the character rather
than the string. This feature makes it useful when receiving binary information.
To rec eive a contro l-C va lue (3), s et bit 1, a ddress 26H.
DBY(38) = DB Y(38 ) .OR . 1
This disables program breaks when a <Ctrl-C> is received.
GET can extract characters from C OM 0 or COM 1. The UI 0 or U I 1 comm and is execute d to get characte rs
from an alternate serial port.
The ASCII value 0 is a valid number. Unfortunately, this value can indicate that there are no c haracters
available. If your application program expects to receive ASC II 0's, the following program will wait until if
there are characters in the buffer to ensure a value of 0 is indeed valid.
100IF COM(0) = 0 THEN 100
110A = GET
Line 100 loops until there is a character in the buffer. Line 110 extracts the character from the buffer. When
A = 0, zero is the ASCII value.
RELATED
COM , COM $, INPUT , UI 1, UI 0
EXAMPLE
The followin g progr am ta kes ch aracters one a t a tim e from the bu ffer and puts them into expan ded m emory.
128K or more of RAM is needed.
100 IF COM(0) = 0 THEN 100
110 A=GET
120 POKEB 1,X,A
130 X=X+1
140 GOTO 100
2-43
Page 63
RPBASIC-52 PROGRAMMING GUIDE
GOSUB
Syntax:GOSUB line number
...
line number program statements
RETURN
Function:Transfers program control to the specified line number. The RETURN causes execution to resume at
the program statement after GOSUB.
Mode:Run
Use:100 FOR A=1 to 20 : GOSUB 200 : NEXT A : END
200 PRINT A, SQR(A) : RETURN
Cards:All
DESCRIPTION
GOSUB provides subroutine capability within RPBASIC-52 programs. A subroutine may be called from
within another subroutine.
GOSUB saves the location of the program statement after G OSU B on the C -Stack and im mediately transfers
program control to line number. When a RETURN is encountered, program execution resumes at program
statement after GOSUB.
GOSUB s can be nested. The number nesting is limited by available C-Stack RAM, but is usually enough for
at least 30 routines.
RELATED
GOTO, ON-GOTO, ON-GOSUB
ERROR
C-STACK An unexpected RETURN is encountered or the number of subroutines executed was excessive.
EXAMPLE
10 GOSUB 100
20 PRINT "Back from routine"
30 END
100 PRINT "In subroutine"
110 RETURN
>run
In subroutine
Back from routine
2-44
Page 64
RPBASIC-52 PROGRAMMING GUIDE
GOTO
Syntax:GOTO line number
Function:Routes program execution to line number
Mode:Command, run
Use:GOTO 100
Cards:All
DESCRIPTION
When line number is the line number of an executable statement, that statement and those follow ing are
executed. GOTO can be used in the comm and mod e to re-enter a program at a desired point.
RELATED
GOSUB, ON-GOTO, ON-GOSUB, RUN
ERROR
INVALID LINE NUMBERSpecified line number does not exist.
EXAMPLE
100 PRINT "At line 100"
200 GOTO 100
2-45
Page 65
RPBASIC-52 PROGRAMMING GUIDE
IDLE
Syntax:IDLE [option]
Where: option specifies a card dependent mode.
Function:Suspends program execution and waits for an interrupt.
Mode:RUN
Use:IDLE
Cards:All. Variations are card dependent.
DESCRIPTION
Different cards have a variety of parameters. Refer to your hardware manual for more information.
Use this command to suspend program execution and wait for an interrupt. An interrupt is from an ONTICK,
ONITR, ON COUN T, ON CO M$, ON LINE , or ON KEYPA D comm and.
RELATED none
ERRORSnone
EXAMPLE
10 ONITR 0,1000
.
.Other initialization
.
200 IDLE Wait for interrupt
.
.On exit from idle, continue program
.
1000 RETISimply exit
2-46
Page 66
RPBASIC-52 PROGRAMMING GUIDE
IF THEN ELSE
Syntax:IF expr [ THEN ] statement(s) [ ELSE statement(s)]
Where: expr = any logical evaluation or variable
statement(s) = any num ber of Basic sta tements
Function:When expr is TRUE (not zero), the instruction following THEN is executed, otherwise the
instruction following ELSE is executed.
Mode:Run
Use:10 IF A<>B THEN PRINT "A=B" ELSE PRINT "A<>B"
Cards:All
DESCRIPTION
THEN is implied by IF. You m ay omit T HEN . ELSE is o ptional. It is included w hen an "eithe r - or"
situation is encountered.
In the case of multiple statements per line following an IF-THEN-ELSE, Basic executes the following
statements only if expr was true. This enables you to conditionally execute multiple statements with a single
expr test. Remember this applies only to Basic statements separated by the {:} delimiter and on the same
program line.
expr can be either a logical evaluation (=, <, >, <>, .AND., .OR., .XOR., or .NOT.) or a variable. Using a
simple variable as a flag can speed up program execution. The following examples illustrate different
execution speeds.
10 A = 1000
20 CLEAR TICK(0)
30 IF A<>0 THEN A=A-1 : GOTO 30
40 PRINT TICK(0)
The above program takes about 1 second to execute, which translates to about 1 m s/ line for this exam ple. If
line 30 were re-written as:
30 IF A THEN A=A-1 : GOTO 30
Execution time is reduced by about 20% by taking away the "<>0" evaluation.
RELATED none
ERRORSnone
EXAMPLE
10 A = 1
20 IF A=0 THEN PRINT "A is 0" ELSE PRINT "A is non-zero"
>run
Is non-zero
2-47
Page 67
RPBASIC-52 PROGRAMMING GUIDE
INPUT
Syntax:INPUT ["prompt text"] [,] [,variable ...]
Where: prompt text = optional text
variable = list of variables to assign
Function:Program pauses to receive data entered from the console inpu t.
Mode:Run
Use:100 INPUT "Enter batch number",$(0)
Cards:All
DESCRIPTION
INPUT brings in numeric and string data from the console serial port during execution. Variables are string,
numeric, or both. Variables are separated by a comma. Optional prompt text must be enc losed i n quot es.
When an optional com ma prece des the first variable, the question mark prompt character is suppressed and
data entry is on the same line as prompt text.
Multiple numeric data may be entered by separating individual values with commas and using <cr> on the
last one. Or, ea ch dat a entry may be ent ered u sing a < cr>.
Strings must be entered with a carriage return.
If you do not enter enough data or the correct type, Basic sends the message TRY AGAIN and prompt text
after which you must enter all the data. If you enter too many characters for the size of allocated STRING
memory, or more numeric values than were requested, Basic discards the extra data, emits the message
EXTRA IGNORE D, and continues execution.
There are two major differences betwe en RPB ASIC-5 2 and BA SIC-52 while using INPUT. Input characters
are buffered. The operator or device may "type ahead" into the buffer and INPUT will respond just that much
quicker. The back- space chara cter (A SCII v alue 08) is recogniz ed in th e sam e wa y as the delete key w as.
This makes editing programs more convenient.
RELATED
COM$, GET, STRING
ERRORSnone
EXAMPLE
10 STRING 200,20
20 INPUT "Enter a number, string, and 2 more numbers: ",A,$(0),B,C
30 PRINT "String:",$(0)
40 PRINT "Numbers:",A,B,C
>run
Enter a number, string, and 2 more numbers: 4,Bob
?7,9
String:Bob
4 7 9
2-48
Page 68
RPBASIC-52 PROGRAMMING GUIDE
INT
Syntax:INT(expr)
Function:Returns an integer portion of expr
Mode:Command, run
Use:PRINT INT(PI)
Cards:All
DESCRIPTION
The integer portion is stored as a floating point number.
RELATED none
ERRORSnone
EXAMPLE
print int(45.67)
45
print int(-16.9999)
-16
To produce true rounding to the closest whole number, use the following formula:
A = INT(B+0.5)
2-49
Page 69
RPBASIC-52 PROGRAMMING GUIDE
KEYPAD
Syntax:A = KEYPAD(function)
Where: function = 0 or 1
0 = return keypad position pressed from buffer
1 = returns number of keys in buffer
Function:Returns keypad pressed position or number of keys in keypad buffer.
Mode:Command, Run
Use:A = KEY PAD(0) Returns a keypad position
Cards:All
DESCRIPTION
The keypad is automatically scanned, debounced, and placed in an 8 position buffer in the background. Key
presses are buffered until retrieved by the KEYPAD(0) function. Keypad positions are returned as a number
from 1 to 24. W hen a 0 is returned , there are no m ore keys in the bu ffer.
Position numbers 1 - 4 correspond to the top row while positions 12 - 16 are the bottom row of keys on the
KP-1 and KP-3 keypads. Thus, the letter 'B' on the KP-1 corresponds to position 8.
Use CL EAR KEY PAD to remove a ll characters from the buffer.
ON KEYPAD branches to a subroutine when a key is pressed. (check card for availability)
RELATED
CLEAR KEYPAD, ON KEYPAD
ERROR
BAD DATA When function is out of range.
EXAMPLE
The following program prints out the keypad position as a key is pressed.
10 CLEAR KEYPAD
20 DO
30 UNTIL KEYPAD(1) = 1
40 PRINT KEYPAD(0)
50 GOTO 20
2-50
Page 70
RPBASIC-52 PROGRAMMING GUIDE
LD@
Syntax:LD@ expr
Where: expr = valid integer address of 00H through 0FFFFH (65535)
Function:Retrieves a floating-point number previously saved with ST@
Mode:Command, run
Use:LD@ 3000
Cards:All
DESCRIPTION
LD@ is used in conjunction with PUSH, POP, and ST@ . Use these commands to save and retrieve floating
point numbers to program RAM.
NOTE: LD@ and ST@ cannot use ex tended RA M. Only segment 0 R AM (used for running B asic
programs) is used. Use PEEKF and POKEF commands to access this memory.
WARNING: Wh en 128 K and 512K RAM are installe d, all of m emory is cle ared on power up and rese t.
Do not use LD@ or ST@ to save floating point numbers in segment 0. Use POKE and
PEEK type comm ands instead.
32K RAM systems have address 7E00H set as M TOP. T his location up to 7F FFH m ay be used to sto re
variables.
expr is the address in RAM of w here a num ber is sto red.
Each floating-poin t num ber req uires si x byte s of m emo ry. expr in the ST@ and LD@ instructions specify the
high address. A number is stored at locations expr through expr-6.
RELATED
ST@, PUSH, POP, PEEKF POKEF
ERROR
BAD ARGUM ENT when expr > 65535
EXAMPLE
100 A=AIN(0)*.234
110 PUSH A
120 ST@7F00H
.
.
300 LD@7F00H
310 POP B
320 PRINT "Analog value retrieved=",B
>run
Analog value retrieved=",B
2-51
Page 71
RPBASIC-52 PROGRAMMING GUIDE
LEN
Syntax:LEN
Function:Returns length of the current program in RAM
Mode:Comm and
Use:PRINT LEN
Cards:All
DESCRIPTION
The LEN function tells yo u the length of the p rogram in R AM. L EN returns a value of 1 wh en no program is
in RAM mem ory (1 is the length of the e nd-of-program marker).
RELATED
FREE
ERRORBAD SYNTAX Attempt to assign a value to LEN
2-52
Page 72
RPBASIC-52 PROGRAMMING GUIDE
LINE (Function)
Syntax:A = LINE(line)
Where: line = 0-9 or 100 to 123 (L ine ran ges m ay var y. Che ck you r hardw are manua l.)
Function:Returns status of a line at on-card lines L0-7 or interrupt port.
Mode:Comm and,Run
Use:A = LINE(2)Reads line 2.
Cards:Basic function available on a ll cards. Range s vary from ca rd to card. See hard ware m anual.
DESCRIPTION
LINE returns a 0 or a 1. A '0' corresponds to a low while a '1' is a high. LINE returns the status of an external
opto rack line or on ca rd lines 0-7. line number corresponds to a position on an external opto rack. For on
card lines, the range is 0 to 9. For an off card rack connected to the digital I/O port, it is num bered 100 to
123. 100 is sim ply ad ded to the op to posi tion nu mbe r to spec ify a position.
When using LINE to return the status of an opto output line, a '0' means the module is ON while a '1'
indicates it is OFF. This is in contrast to the LINE statement which turns on a module with a '1'. When
reading an opto input module, a '0' indicates there is no voltage applied to the inputs.
LINE returns true logic for L0-L7. A "0" is a logic low while a "1" is a logic high. Line 8 returns the status
of INT0 and/or ISOA/B input. Line 9 returns the status of INT 1.
LINE(n) and LINE #(n) may be used interchan geably in a prog ram. For exa mple, you m ay have an external 8
position opto rack and use some of the n on opt o digita l lines fo r switch inputs.
RELATED
LINE#, LINEB functions, LINE, LINE#, LINEB statements, CONFIG LINE
ERRORS
BAD SYNTAXWhen '(' or ')' are missing
BAD DATAWhen line is out of range for a port.
EXAMPLE
The following example show how LINE and LINE# may be used
10 CONFIG LINE 100,12,0,0,1 Configure I/O port
20 PRINT LINE(104)Read external opto rack position 4
30 PRINT LINE#(119)Read digital I/O port line 19 (Port A.0)
40 LINE 100,1Turns on opto module at external rack position 0
50 LINE#110,1Turns on high current output at I/O port line 10.
2-53
Page 73
RPBASIC-52 PROGRAMMING GUIDE
LINE# (Function)
Syntax:A = LINE#(line)
Where: line = connector number from 101 to 125 (Line ranges may vary. Check your hardw are
manual.)
Function:Returns status of a line at the digital I/O connector.
Mode:Comm and,Run
Use:A = LINE#(103) Reads level from digital I/O port connector number 3.
Card:Function ava ilable on all cards. R anges will vary from card to card. See hardware manu al.
DESCRIPTION
The '#' modifier to LINE specifies the actua l line nu mbe r at the d igital I/O port co nnec tor. line must range
from 101 to 125 or else a BAD ARGUMENT is returned. Line 102 is also not valid. LINE# cannot be used
for the on card opto rack (0 - 3). The line number is com puted by sim ply adding 100 to the connec tor pin
number.
LINE# returns a '0' or a '1', which correspond directly to the logic level at the connector. When using LINE#
to return the status of an opto output line, a '0' means the module is ON w hile a '1' indicates it is OFF . This is
in contrast to th e LIN E state ment which turns o n a m odule with a '1'. Whe n reading an opto input module , a
'0' indicates there is no voltage applied to the inputs.
The following example returns the status at digital I/O connec tor J3, pin 19 (82C5 5 port A, bit 0);
A = LINE#(119)
See LINE function for more program exam ples.
RELATED
LINE, LINEB functions, LINE, LINE#, LINEB statements, CONFIG LINE
ERRORS
BAD SYNTAXWhen # is used for on card positions.
BAD DATAWhen line is out of range for a port.
2-54
Page 74
RPBASIC-52 PROGRAMMING GUIDE
LINEB (Function)
Syntax:A = LINEB(i/o bank,add ress)
Where: i/o bank = 0 to 7. Specific functions are card de pendent. Re fer to your hardw are manu al.
address = device dependent. Usually it is 0 to 3.
Function:Reads a byte from an I/O device.
Mode:Command, Run
Use:A = LINEB (3,0) Reads port A of 8255 at digital port.
Cards:All. i/o bank is unique to each card.
DESCRIPTION
This function is equivalent to INP in other BASICs. Data is read 8 bits at a time in contrast to other LINE
functions which return 1 bit at a time. The i/o bank selects a particular I/O device listed in your hardware
manual.
Use this command to read devices and obtain data not otherwise available using RPBASIC-52.
RELATED
LINE, LINE# (function), LINE, LINE#, LINEB (statement), CONFIG LINE
ERROR
BAD ARGUMENT i/o bank > 7
EXAMPLE
The following example reads all 8 lines at port A on the digital I/O port.
100 A = LINEB(3,0)
2-55
Page 75
RPBASIC-52 PROGRAMMING GUIDE
LINE (Statement)
Syntax:LINE line,data
Where: line = 0 to 8 or 100 t o 123 (L ine ran ges m ay var y. Che ck you r hardw are m anua l.)
data = 0, 1, ON, or OFF. See text below.
Function:Turns a external opto module or lines L0-L8 on or off.
Mode:Command, Run
Use:LIN E 0,1
Cards:Basic statemen t availa ble for a ll cards . line ranges are card dependent. See hardware manual.
DESCRIPTION
LINE is used to control an external output opto module or on card lines 0-8. On board opto positions are
numbered 0-3. Off card opto racks using the digital I/O port are numbered 100 to 123. 100 is simply added
to the opto position to identify the external rack. For example,
LINE 105,0
turns external opto rack position num ber 5 off.
data is ON, OFF, 0, or 1. ON is equivalent to 1 while OFF is 0. A '0' value turns off a module while a '1'
turns it on. These values are in contrast to the LINE# statement, which has the opposite meaning. For lines
0-7, "O N" se ts a line to a 1 w hile "O FF" sets it to 0 .
LINE 8,0 turns off the high curren t port. L INE 8,1 turn s it on.
Using ON or OFF instead of numbers or variables speeds up this statement by 20%.
LINE and LINE # ma y be us ed interchangeably in a program .
RELATED
LINE, LINE#, LINEB (function), LINE#, LINEB (statement), CONFIG LINE
ERROR
BAD ARGUMENT When line is out of range
EXAMPLE
The following example shows how different data is returned.
10 LINE 118,OFFTurns off external opto module 18.
20 LINE #118,0Sets digital I/O connector line 18 to 0.
30 PRINT LINE(118),LINE#(118)
run
1 0
The function LINE(118) returns a 1 because that is the necessary condition to turn off a module. Also notice
that LINE(118) returns the status at opto port position 18 while LINE#(118) returns the condition at the
digital I/O port connector pin 18.
Use the CONFIG LINE statement to configure lines as inputs and outputs. Refer to the Digital I/O lines
section in the manual and CONFIG LINE statement for more information.
2-56
Page 76
RPBASIC-52 PROGRAMMING GUIDE
LINE# (Statement)
Syntax:LINE# line,data
Where: line = 101 to 125, is the digital I/O line connector number. (Line ranges may vary. Check
your ha rdwa re ma nual.)
data = ON, OFF, 0, or 1. See text below.
Function:Sets a specified line at the digital I/O connector high or low.
Mode:Command, Run
Use:LIN E #10 2,0
Card:Basi c com mand avai lable fo r all cards. line ranges are card dependen t. Refer to hardw are manu al.
DESCRIPTION
LINE # addresse s the dig ital I/O conne ctor pins. line must be between 101 and 125. Line 102 is not valid (it
is the +5 V supply).
data is either ON, OFF, 0 or 1. ON is the same as a 1 while OFF is a 0. '0' sets the line low w hile a '1' sets it
high. This is the opposite of the LINE command. Opto modules require a low , or '0' level to turn on. LINE
inverts data while LINE # does not. Using ON and OFF speeds up statement execution by about 20%.
LINE and LINE # ma y be us ed interchangeably in a program .
RELATED
LINE, LINEB (function), LINE, LINEB (statement), CONFIG LINE
ERRORS
BAD ARGUMENT When line is out of range
BAD SYNTAX When # is used for on card opto rack
EXAMPLE
The following example shows how different data is returned.
10 LINE 118,OFF Turns off external opto module 18.
20 LINE #118,0Sets digital I/O connector line 18 to 0.
30 PRINT LINE(118),LINE#(118)
run
1 0
The function LINE(118) returns a 1 because that is the condition to turn off a module.
2-57
Page 77
RPBASIC-52 PROGRAMMING GUIDE
LINEB (Statement)
Syntax:LINEB i/o bank,a ddress,da ta
Where: i/o bank = 0 to 7. Specific functions are card de pendent. Re fer to your hardw are manu al.
address = device dependent. Usually it is 0 to 3.
data = 0 to 255, data to output.
Function:Writes a byte to an I/O device.
Mode:Command, Run
Use:LIN EB3 ,0,AWrites value in A to port A of 8255 at digital port.
Card:Basic command available for all cards. Device/Function changes slightly for each card. Refer to the
hardware m anual.
DESCRIPTION
This statement is equivalent to OUT in other BASICs. Data is written 8 bits at a time. LINE and LINE #
write 1 bit at a time. The i/o bank selects a particular I/O device listed in yo ur hardware m anual.
Use this command to access or program devices into modes not directly supported by RPBASIC-52.
RELATED
LINE, LINE#, LINEB (function), LINE, LINE# (statement), CONFIG LINE
ERROR
BAD ARGUMENT i/o bank > 7, data > 255 or negative
EXAMPLE
The following example writes the value in variable 'C' to port B on the digital I/O co nnector.
100 LINE B3,1,C
2-58
Page 78
RPBASIC-52 PROGRAMMING GUIDE
LIST
Syntax:LIST
LIST line number
LIST line number - line number
Where: line number is a program line number
Function:Prints all or some of a program to the console.
Mode:Comm and
Use:LIST 10-100
Card:All
DESCRIPTION
The LIST comm and prints the program in RAM to the console device. LIST inserts spaces after the line
number and before and after instructions. Program listings are terminated with a <Ctrl-C>.
LIST line number lists the program line number to the end of the program. LIST line number-line number
lists the program from the first line num ber to the second line numbe r.
RELATED
LIST#
2-59
Page 79
RPBASIC-52 PROGRAMMING GUIDE
LIST#
Syntax:LIST# port
LIST# port,line number
LIST# port,line number-line number
Where: port = 0 or 1 or number of serial ports on your card.
line number = program line number
Function:Outputs the currently selected program to the serial printer port.
Mode:Comm and
Use:LIST#0
Cards:All. port limit is card dependent
DESCRIPTION
The L IST# com man d outp uts all o r som e of the currently prog ram in RA M to t he spe cified s erial port. port 0
is the console port.
LIST# inserts spaces after the line number and before and after instructions. LIST#port, line number lists the
program from the line number to the end of the program. LIST#port,line number - line number lists the
program from the first line number to the second line number. These line numbers must be separated by a
dash(-).
RELATED
LIST
2-60
Page 80
RPBASIC-52 PROGRAMMING GUIDE
LOAD
Syntax:LOAD [segme nt]
Where: segment = 0 to 7, see table below.
Function:Loads a program from EPROM
Mode:Comm and
Use:LOAD 1Loads program from memory segme nt 1
Card:All. Maximum segment is card depend ent. Refer to your c ards hardwa re manua l.
DESCRIPTION
Up to 8 different programs can be saved and loaded from flash EPROM. The maximum number depends
upon the EPROM size. When no segment is specified, 0 is assumed.
Use LOAD to retrieve programs for editing. LOAD overw rites and replaces the previous program. You
cannot merge programs. Programs are saved to flash EPROM using the SAVE n comm and.
For more information on segments and EPROM sizes, see the SAVE command.
RELATED
SAVE, EXECUTE
ERROR
BAD ARGUMENT segment > 7
2-61
Page 81
RPBASIC-52 PROGRAMMING GUIDE
LOG
Syntax:LOG (expr)
Function:Returns the natural logarithm (base "e") of expr which must evaluate to greater than zero. Calculated
to seven significant digits.
Mode:Command, run
Use:PRINT LOG (COS(0))
Cards:All
ERRORS
ARITH. UNDERFLOW expr or result is less than RPBASIC-52's smallest floating-point value of ± 1E-127
ARITH. OVERFLOWexpr or result is greater than RPBASIC-52's largest floating point value of ±
.99999999E+127
BAD ARGUMENTAttemp t to take LO G() of zero
EXAMPLE
100PRINT EXP(-200), LOG(1.383901E-87)
>run
1.383901 E-87 -200
2-62
Page 82
RPBASIC-52 PROGRAMMING GUIDE
MTOP
Syntax:MTOP
MTOP = last valid RAM address
Function:Reads or assigns the top of external data memory which will be used by Basic for variable, string,
and RAM program storage
Mode:Command, run
Use:MTOP =30000
PRINT MTOP
Cards:All. Command is limiting on cards with 128K or more of RAM.
DESCRIPTIONS
The MTOP system control value is the maximum external data mem ory address which RPB ASIC-52 w ill use
for RAM program spa ce and variab le and string storage . MTO P is not necessa rily the top of available
external data memory. On cards with 32K of RAM, MTOP is automatically set to 7E00H on power up. On
cards with 128K or more of RAM, MTOP is set to 0FFFFH on power up.
RELATED
ST@, LD@
ERROR
MEMORY ALLOCATION MTOP has been assigned a value greater than top of external data memory.
EXAMPLE
? MTOP
65535
2-63
Page 83
RPBASIC-52 PROGRAMMING GUIDE
NEW
Syntax:NEW
FunctionErases current program in RAM. All variables and strings are cleared.
Mode:Comm and
Use:NEW
Cards:All
DESCRI PTIO N
The NE W com mand de letes the program currently in RA M, sets all variab les equal to zero, an d clears all
strings and m ulti-tas king in terrupt s. NE W d oes no t effect the rea l-time clock or string alloca tion.
RELATED
CLEAR
2-64
Page 84
RPBASIC-52 PROGRAMMING GUIDE
NULL
Syntax:NULL integer
Where: integer = 0 -255
Function:Sets number of NULL characters output to user after a carriage return
Mode:Comm and
Use:NULL 100
Cards:All
DESCRIPTION
The N ULL comman d cont rols how many NU LL c harac ters (00 H) are output following a carriage return.
After a reset, N ULL = 0. Because this is a com man d mo de com man d, it can not be used as part of a program.
The NULL count is stored at external data memory location 15H. Change the value of NULL in a program
using the DB Y(21)=expr instruction, where expr is any value between 0 an d 255. No error is returne d if it is
greater than 255.
NULL is generally needed only if you have a slow printer connected to the serial printer port. Note that
NULL affects all serial ports.
Some terminal programs will advance the cursor when a null character is received. This may result in an
strange looking display.
RELATED
LIST, PRINT
ERROR
BAD SYNTAX When integer is negative.
2-65
Page 85
RPBASIC-52 PROGRAMMING GUIDE
ON COM$
Syntax:ON COM$port,length,terminator,program line
ON COM$port
Where: port = the com port numbe r 0 or 1
length = number of received characters for an interrupt
terminator = character to cause an interrupt
program line = executes subroutine when length or terminator is met.
Function:Branches to a subroutine when length or terminator criteria is met.
Mode:Run
Use:ON CO M$0,5,13,1000Executes su broutine at line 100 0 when eith er 5 characters or a <CR > is
received.
Cards:RPC-320, RPC-330
DESCRIPTION
ON COM$ is a mu ltitaski ng stat eme nt. length and terminator parameters are checked on every received
character in the background. If either parameter is met, the program branches to the program line designated.
The first syntax enables ON COM $ while the se cond one turns it off.
When terminator is 0, then character values are not checked. Only a length criteria will cause a n interrupt.
Review HARDWAR E AND SOFTWARE INTERRU PTS in the first part of this manual for interrupt
handling and multitasking information. A far more extensive example is shown earlier in this manual under
Serial Multitasking.
RELATED
COM$
ERROR
BAD ARGUM ENT when length or terminator > 255.
EXAMPLE
The following example executes a program at line 1000 when either 5 characters or the <C R> cha racter is
received. The received string is transferred to $(0) minus the <CR > character.
Syntax:ON COUNT number, line number, count, program line
ON COUNT number, line number
ON COUNT number
Where: number is 4 to 11. It represents a cou nter numbe r.
line number is 0-7 or 100-123 and is the digital I/O line number.
count is 1 to 65535. It is the number of pulses needed for an interrupt.
program line is the subroutine to execute when count is reached.
Function:Enables count multi-tasking at a specific I/O line. Optionally generates a software interrupt when the
specified number of counts at an I/O line is reached.
Mode:Run
Use:ON CO UNT 10,7,200,5000Executes a subroutine at line 5000 when 200 counts are reached at I/O
line 7.
Cards:RPC -320, R PC-330. line number is card depend ent. Refer to your h ardware m anual.
DESCRIPTION
This command enables software counting. This command is not related to any hardware counters on the card.
The three syntaxes control counting as follows: T he first syntax with a ll parameters g enerates a softw are
interrupt when count is reached. The second syntax simply enables counting at the line number. The third
syntax turns off count multi-tasking for that number only.
A pulse is counted on a high to low transition. A line must be high and low for a m inimum of 5 ms to ensure
detection. The RPBASIC-52 operating system scans the specified lines every 5 ms. Thus, maximum
counting frequency is 100 Hz. In practice, maximum is 95 Hz using a perfect square wave.
The current number of pulses at a counter number is read using the COUNT function. To reset or zero a
count value, re-execute ON COU NT aga in for that particular number.
number is from 4 to 11 to distinguish it from the other hardware counters on board.
Review HARDWAR E AND SOFTWARE INTERRU PTS in the first part of this manual for interrupt
handling and multitasking information. Read COUNT MULTITASKING earlier in this manual for a summ ary
of operation.
RELATED
COUNT function
ERROR
BAD ARGUM ENT when number is out of range.
EXAMPLE
The following example sets line 0 as a counter and branches to a subroutine when this line is brought low 10
times
10 ON COUNT 4,0,10,1000
20 IDLE
30 GOTO 20
.
.
.
1000 PRINT "Counter 4 interrupt"
1010 RETURN
This example makes line 3 a counter only input. Its value is printed every second using COUNT function.
2-67
Page 87
RPBASIC-52 PROGRAMMING GUIDE
10 ON COUNT 10,3
20 ONTICK 1,1000
30 GOTO 30
.
.
.
1000 PRINT COUNT(10)
1010 RETURN
2-68
Page 88
RPBASIC-52 PROGRAMMING GUIDE
ONERR
Syntax:ONERR line number
Function:Goes to line number on arithmetic error, bad argument, and hardw are erro rs.
Mode:Run
Use:ONER R 1000
Cards:All
DESCRIPTION
The ONER R instruction traps arithmetic errors and hardware problems, transferring control to line number.
ONERR can be used to handle errors generated due to bad user input from and INPUT instruction. ONERR
is a GOTO, not a GOSUB. Consequently, there is no easy way to resume program execution. The control
and argument stacks are cleared so all GOSUB's, FOR-NEXT loops, etc. are cleared.
Error codes are stored at external memory location 257 (101H) and are accessed using the XBY instruction.
Where: expr = 0 to number of subroutines after GOSUB
linen = subroutine line number to e xecute
Function:Calls subroutine based on value of expr.
Mode:Run
Use:ON A G OSUB 100, 200, 500
Cards:All
DESCRIPTION
The ON-GOSUB instruction conditionally branches to one of several possible subroutines depending on the
value of expr. expr must evaluate to greater than o r equal to zero. If expr evaluates to zero, execution
branches to line0. When expr evaluates to one, execution branches to line1, etc. If necessa ry, expr is truncated
to an integer.
ON-GOSUB saves the location of the program statement after ON-GOSUB on the control stack and
immediately transfers program control to the selected subroutine. The subroutine is then executed. When
Basic encounters the RETURN instruction, program execution resumes at the program statement after ONGOSUB . ON-GOSUB instructions can be nested.
One or more of linen may be the same, to execute the same subroutine w ith different expr values. At least
one linen must be pro vided. linen can be in any order.
RELATED
ON GOTO, GOSUB, RETURN
ERRORS
BAD ARGUMENT The value of expr is less than 0
BAD SYNTAXThe expr value is larger than the number of subroutine locations provided, or commas
were omitted between {subr n line#} values, or no subroutine locations were given.
C-STACKAttempted recursion caused control stack overflow
EXAMPLE
10 P=2
20 ON P GOSUB 1000, 3000, 2000
30 END
1000 PRINT "Line 1000"
1010 RETURN
2000 PRINT "Line 2000"
2010 RETURN
3000 PRINT "Line 3000:
3010 RETURN
>run
Line 3000
2-70
Page 90
RPBASIC-52 PROGRAMMING GUIDE
ON GOTO
Syntax:ON expr GOTO line0[,line1[line2...]]
Function:Branches to a program line based on expr value.
valuate to greater than or equal to zero; if expr evaluates to zero, execution bran ches to {0th line# }; if expr
evaluates to one, execution branches to {1st line#}, etc. Commas shown are required.
Mode:Run
Use:ON A/5 GO TO 100, 200, 500
Cards:All
DESCRIPTION
The ON-GOTO instruction conditionally branches to linen where 'n' is the value of expr. The expr must
evaluate to greater than or equal to zero. When expr evaluates to zero, execution branches to line0. Whenexpr evaluates to one, execution branches to line1, etc. If necessary, expr is truncated to an integer.
One or more of the program lines may b e the same , to GOTO the same location with differe nt expr values.
At least one program line must be provided. Program lines may occur in any order, for example, ON A
GOTO 500,700,600.
RELATED
GOTO, GOSUB, ON-GOSUB
ERRORS
BAD ARGUMENT The value of expr is less than 0.
BAD SYNTAXThe expr value is greater than the number of {"nth" line#} numbers provided, or
commas were omitted between {line#} values, or no line numbers were provided after
the ON-GOTO.
EXAMPLE
10 P=2
20 ON P GOTO 1000,2000,3000
30 END
1000 PRINT "Line 1000"
1010 END
2000 PRINT "Line 2000"
2010 END
3000 PRINT "Line 3000"
3010 END
>run
Line 3000
2-71
Page 91
RPBASIC-52 PROGRAMMING GUIDE
ONITR
Syntax:ONITR number,line number
ONITR number
ONITR line number
ONITR
Where: number = interrupt line. This is ca rd dependen t. Refer to your hardw are manual.
line number = Subroutine line number to go.
Function:Branches to a service subroutine on an external or counter interrupt.
Mode:Run
Use:ONITR 0,5000Executes a subroutine at line 5000 on hardware interrupt 0.
Cards:Basic com man d avai lable fo r all cards. number may or m ay not be used. Refer to your hardw are
manual for more information.
DESCRIPTION
ONITR provides a way to respond to hardware interrupts. It replaces ONEX1 in BASIC-52. Interrupts can
be external through the opto isolator, external TTL, or any number of card dependent sources. The number of
interrupts available depend upon the card type. Refer to your hardware manual for specific information.
The first two syntaxes are for the RPC-330. The second two are for the RPC-320 and RPC-52.
Hardware interrupts are edge sensitive and latched. When the current R PBA SIC program statement is
completed, execution branches to the subroutine specified by line number. Interrupt latency is determined by
the current pro gram statem ent. Th e IDL E com mand provi des the fastest respon se to an interrup t.
You must exit an ONITR using the RETI statement. Failure to do so prevents other ONITR and ONTICK
interrupts.
To turn off ON ITR, refer to the ca rd's hardware m anual.
ONITR can be interrupted only by an ONTICK interrupt. Also, ONITR can interrupt any other multi-tasking
statement (ON LINE, ON C OM$, O N KEY PAD, etc.) but cannot be interrupted by them . An interrupt pulse
to the card must be at least 1 m icro-second long , low level.
RELATED
RETI
ERRORS
none
2-72
Page 92
RPBASIC-52 PROGRAMMING GUIDE
EXAMPLE
The following example responds to an external interrupt on the RPC-330.
10 ONITR 1,1000Declare interrupt
.
.Other program initialization
.
200 IDLEWait for interrupt
210 IF F = 0 THEN 200 If not done
.
.Program continues
.
990 END
1000 PRINT "In interrupt"Print something
1010 C=C+1Increment counter
1020 IF C=5 THEN F=1Set flag on 5 times
1030 RETI
2-73
Page 93
RPBASIC-52 PROGRAMMING GUIDE
ON KEYPAD
Syntax:ON KEYPAD subroutine line
ON KEYPAD
Where: subroutine line = program to execute
Function:Branches to a subroutine when a keypad switch is pressed.
Mode:RUN
Use:ON KE YPAD 1000
Cards:RPC-320, RPC-330
DESCRIPTION
Program branches when any key is pressed on the keypad. Use the routine below to build a string.
Review HARDWAR E AND SOFTWARE INTERRU PTS in the first part of this manual for interrupt
handling and multitasking information.
RELATED
KEYPAD, CLEAR KEYPAD
ERRORS
none
EXAMPLE
The following program sets up a string array and keypad multi-tasking. When the enter key is pressed, the
string is printed. Keypad position 16 is designated as enter while 12 is clear.
10 STRING 200,20Initialize string area
20 $(0) = "123A456B789C*0#D"Initialize keypad string
30 P = 1String position pointer
40 ON KEYPAD 500Declare interrupt
50 PRINT "Enter a number from the keypad",
REM Rest of program continues
REM Scan keypad flag
210 IF PF = 0 THEN 210Check flag. Prints string
220 PRINTwhen 'enter' is pressed.
230 PRINT "Entered string is: ",$(2)
240 PF = 0
250 GOTO 210
500 A = KEYPAD(0)Get keypad character
520 IF A = 12 THEN 600 : REM Process clearAdd other traps as needed
530 IF A = 16 then 700 : REM process enter
540 A=ASC($(0),A)Get ASCII equivalent
550 PRINT CHR(A),
560 ASC($(2),P) = APut into keypad input $
570 P = P + 1Update position pointer
580 ASC($(2),P) = 13Set CR as end of string
590 RETURN
600 REM Clear input string
610 $(2) = ""
620 P = 1
630 RETURN
700 REM 'Enter' processing
710 P = 1
720 PF = 1
730 RETURN
2-74
Page 94
RPBASIC-52 PROGRAMMING GUIDE
ON LINE
Syntax:ON LINE number,I/O line,subroutine line
ON LINE number
ON LINE ON/OFF [,CLEAR]
Where: number = 0 to 7, is the interrupt reference number
I/O line = 0 to 7 or 100 to 123. Line num ber range is card d ependent.
subroutine line = program subroutine to execute on line change
ON/OFF = enable / suspend ON LINE checking
CLEAR = clears all line change flags
Function:Branches to a service subroutine when an I/O line changes state.
Mode:RUN
Use:ON LINE 3,7,5000Executes a subroutine at line 5000 when line 7 changes.
Cards:RPC-320, RPC-330
DESCRIPTION
Up to 8 digital I/O lines can be monitored for changes in state. Lines are monitored by the operating system
every 5 ms. When a line changed from the last monitored state, a flag is set. This flag is checked at the end
of the current Basic statement. Thus, an interrupt is generated when a line goes low or high. Unless an
ONTICK or ONITR subroutine is currently executing, the subroutine line is then executed.
number is from 0 to 7. It acts, to some extent, as a priority arbitrator. It does not have any relationship to I/O
line or subroutine line except to number interrupts. More information later.
An ON LINE interrupt is turned off by specifying number only. ON LINE interrupts can be turned off any
time in a program.
I/O line numbers 100-123 correspond to opto rack positions. Use the table in the DIGIT AL I/O chapter to
make the correspondence between an opto position and actual digital I/O line. Lines 0-7 are designated L0L7 on the card.
ON LINE ON/OFF enables/suspends line interrupts. Lines are still checked every 5 ms by the operating
system . If a line d id cha nge, it is flagge d. ON LINE OFF suspends interrupts while ON LINE ON resumes
this type of interrupt. Use ON LINE OFF when an I/O line interrupt cannot be preempted by any other line
interrupt. ON LINE ON resumes interrupts. When this command is executed, any changed lines cause an
interrupt. To cancel or clear interrupts, use the CLEAR parameter shown abo ve. All line chan ge flags are
reset and no interrupts are generated until a line changes state.
When two lines chang e betw een th e 5 m s sampling time, th e high er num bered interrupt takes priority .
However, if the same or another line changes in the next sample period, its subroutine will take priority.
For an interrupt to occur, a line must be stable for at least 5 ms. When a line changes faster than this, one or
both of the following scenarios happen: Sinc e lines are sam pled every 5 ms, a p ulsed s ignal can be m issed.
Use one of the ONITR interrupts to capture this kind of signal. The second scenario is more of a problem.
ON LINE generates subroutines. When a line change is detected, a subroutine is generated. When the
subroutine is long and a line change quick enough, these routines become nested. When too many routines
are stacked, program execution is terminated and a control-stack error is returned. Maximum nesting level
depends upon other control structures currently running. 30 levels is a reasonable number. However, if a
number of FOR-NEX T loops are running, this number is diminished.
There are two ways to take care of this program. First, make the service routine very short - less than 3
commands. Second, is to execute the ON LINE OFF com mand. This shuts off all ON LINE execution.
2-75
Page 95
RPBASIC-52 PROGRAMMING GUIDE
The overall speed of RPBASIC-52 slows down by about 3% when all ON LINE tasks are enabled.
Review HARDWAR E AND SOFTWARE INTERRU PTS in the first part of this manual for interrupt
handling and multitasking information.
RELATED none
ERRORS
BAD ARGUM ENT when number > 7 or I/O line is not between 0-7 or 100-123.
EXAMPLE
The following example sets up several interrupts.
10 ON LINE 0,1,1000
20 ON LINE 5,2,2000
30 ON LINE 3,3,3000
.
.
.
1000 PRINT "In LINE 0 interrupt"
1100 RETURN
2000 PRINT "In LINE 5 interrupt."
2010 PRINT "Suspending other line interrupts."
2020 ON LINE OFF
.
.
.
2300 PRINT "Resuming line interrupts."
2310 ON LINE ON , CLEAR
2320 RETURN
3000 PRINT "In LINE 3 interrupt."
3010 RETURN
Lines 10-30 set up ON LINE interrupts for lines 1, 2, and 3. For this example, line 5 cannot be interrupted by
any other line changes. Line 2020 suspends interrupts. The program continues to process this subroutine and
lines are still checked for changes. Line 2310 resumes line interrupts but it also clears out previous changes.
2-76
Page 96
RPBASIC-52 PROGRAMMING GUIDE
ONTICK
Syntax:ONTICK time,line number
Where: time = time interval from 0.01 to 327
line number = line to branch
Function:Calls subroutine at line number every time interval.
Mode:Run
Use:ONTICK 1.25,500
Cards:All
DESCRIPTION
ONTICK calls a subroutine every time interval. time ranges from 0.010 seconds to 327.7 seconds
(approxima tely 5.5 minu tes). time can be specified in increments as small as 0.005 seconds. ONTICK
interrupts are turned off when time = 0. A line number must still be provided even though it is not used.
The interval period can be reset at any time in a program. When an ONTICK statement is executed, an
interrupt will occur in time seconds. Time accumulated since the last interrupt is discarded.
NOTE: Use th e RE TI com man d to exit this subroutine. Failu re to do so prev ents fu ture O NTI CK interrup ts.
Make sure your ONTICK subroutine can finish before the next interrupt. If the program is in the subroutine
longer than the specified time interval, the next one will be missed.
This interrupt has the highest priority of any others. ONITR can interrupt any other routine, but no other
interrupt can take over this one.
RELATED
RETI
ERRORS
BAD ARGUMENT When time > 327.6 or negative
BAD SYNTAXWhen any parameters left out
INVALID LINEWhen line number not found
EXAMPLE
The following example will interrupt 5 times before it is canceled at line 220.
10 A = .15
20 ONTICK A,200
30 IF C<4 THEN A=A+1 : GOTO 30
40 END
200 PRINT A
210 C = C + 1
220 IF C = 5 THEN ONTICK 0,200
230 RETI
>run
145.15
286.15
431.15
575.15
The IDLE com mand m ay be used to " wait" for an O NTICK interval interrupt.
2-77
Page 97
RPBASIC-52 PROGRAMMING GUIDE
PEEKB
Syntax:PEEKB(segment,ad dress )
Where: segment = 0 to 7, specifies a 64K segment
address = 0 to 65535, byte address in a segment
Function:Reads a byte from RAM
Mode:Command, Run
Use:A = PEEKB(1,AD)
Cards:All
DESCRIPTION
This function is used in conjunction with POKEB. Data is retrieved from any memory location. PEEKB
inputs 1 byte of data. This function operates in much the same way as XB Y does except PE EKB c an access
512K of RAM.
See POKEB command for addressing and segment info.
RELATED
POKEB
ERRORS
BAD SYNTAXIf B, segment, or address is missing.
BAD DATAIf segment is > 7, or address > 65535
EXAMPLE
The following example reads digital I/O port A and saves it to RAM. The values are then retrieved and
printed back.
10 FOR N=0 TO 500
20 POKE B1,N*2,LINEB(3,0)
30 NEXT
40 FOR N=0 TO 500
50 A=PEEKB(1,N*2)
60 PRINT A,
70 NEXT
2-78
Page 98
RPBASIC-52 PROGRAMMING GUIDE
PEEKF
Syntax:PEEKF(segment,ad dress)
Where: segment = 0 to 7, specifies a 64K segment
address = 0 to 65535, byte address in a segment
Function:Reads a floating point number from RAM. Floating point range is + /- 1E-127 to +/-
0.99999999E+127
Mode:Command, Run
Use:A = PEEK F(1,AD)
Cards:All
DESCRIPTION
This function is used in conjunction with POKE F. Data is retrieved from any memory location. PEEK F
retrieves a floating point number saved by POKE F.
PEEKF can access up to 512K of ram by selecting a segment and an address. A segment selects a 64K block
while the address selects a location within this block.
Each floating point num ber req uires 6 bytes. address must be incremented indexed 6 byte s for eac h valu e.
See POKEB and POKEF com mands for addressing and segment info.
RELATED
POKEF
ERRORS
BAD SYNTAXIf B, segment, or address is missing.
BAD DATAIf segment is > 7, or address > 65535
EXAMPLE
The following example reads the A -D port, multiplies it by a constant, and sa ves it to RA M. The v alues are
then retrieved and printed back.
10 FOR N=0 TO 500
20 A = AIN(1) * 0.2344
20 POKE F1,N*6,A
30 NEXT
40 FOR N=0 TO 500
50 A=PEEK F(1,N*6)
60 PRINT A,
70 NEXT
2-79
Page 99
RPBASIC-52 PROGRAMMING GUIDE
PEEKW
Syntax:PEEKW(segment,ad dress )
Where: segment = 0 to 7, specifies a 64K segm ent.
address = 0 to 65535, w ord address in a segment.
Function:Reads an unsigned 16 bit number from RAM
Mode:Command, Run
Use:A = PEEKW(0,AD)
Cards:All
DESCRIPTION
Use this function in conjunction w ith POK EW . Data is retrieved from any mem ory location as a single 16 bit
(2 byte) number. Numbers in the range of 0 to 65535 are retrieved. Two bytes of data are required for data
retrieval.
PEEKW can access up to 512K of ram by selecting a segment and an address. A segment selects a 64K block
while the address selects a location within this block.
See POKEB for addressing and segment information.
RELATED
POKEW
ERRORS
BAD SYNTAXIf W, segment, or address is missing.
BAD DATAIf segment is > 7, or address > 65535
EXAMPLE
This exam ple takes 500 rea dings from an alog input 0, saves it to se gment 1 o f a 128K R AM, and then prints
out all of the values
10 FOR N=0 TO 500
20 POKE W1,N*2,AIN(0)
30 NEXT
40 FOR N=0 TO 500
50 A=PEEKW(1,N*2)
60 PRINT A,
70 NEXT
2-80
Page 100
RPBASIC-52 PROGRAMMING GUIDE
PEEK$
Syntax:$(n) = PEEK$(segment,ad dress)
Where: segment = 0 to 7, specifies a 64K segment
address = 0 to 65535, starting string address in a segment
Function:Retrieves a string from RAM.
Mode:Command, Run
Use:$(0) = PEEK$(1,210)
Cards:All
DESCRIPTION
Use th is com man d to retri eve str ings stored in R AM mem ory using the POKE$ comm and. segment specifies
the 64K segment to save to. 0 is the base segment where RPBA SIC-52 runs its programs. Setting MTOP to a
number less than the top of memory will provide a 'protected' area from the Basic program.
Refer to the POKEB statement for addressing and segment information.
NOTE: This command works only when it is assigning another string variable. A BAD
SYNTAX error is returned when it is part of a PRINT, IF-THEN, ASC, or other command
or function. Use this function only as shown in SYNTAX above.
RELATED
POKE$
ERRORS
BAD SYNTAX If $, segment, or address is missing. Also when this function is part of
another function or command.
BAD DATAIf segment is > 7
EXAMPLE
The following example assumes MTOP = 30000. It will assign and recover a string from
RAM.