CopYTight © IFAC Theory and Application of Digital ContTol New Delhi, India 1982
A SIMPLE CONTROL LANGUAGE FOR MICROPROCESSORS AND ITS APPLICATIONS D. W. Clarke Department of Engineering Science, Parks Road, Oxford OX1 JP], UK
Abstract A language - Control Basic - is described which is suitable for the lowcost single-board microcomputers typically used in simple control systems. It allows for direct program access to peripheral devices and memory locations and has a range of useful real-time features which provide for background/foreground operations within the same user program. The paper describes the design of the languages and its implementation on 8-bit microcomputers based on the Intel 8080 and its derivatives. Applications to data acquisition and control systems in education and research are described . Keywords Adaptive control; computer control; computer software; microprocessors; programming control; programming languages. INTRODUCTION Although microprocessors have considerably reduced the hardware cost of typical digital control systems, software costs have not fallen proportionally. This is particularly true for one-off systems (typical of education and research) where the cost cannot be amortized over a range of units, so much effort has been devoted to the production of appropriate software tools to improve programmer productivity and to minimise software maintenance. It is accepted that structured languages such as PL/M, Pascal and Modula are the most effective tools, particularly when compared with unstructured assembly code, but they are expensive, involving large amounts of memory for compiling user programs and a disc-operating system for storing text-editors, programs and compliers. In particular it may be difficult to modify a compiled program at a remote site. For very low-cost systems there is still a role for ,simple interpretive languages such as Control Basic, whose syntax (Clarke and Frost, 1979, Clarke, 1980), implementation and application is described in this paper. For many one-off systems the most cost-effective building-block is the 'single-board-computer', such as those in the Intel SBC range. SBC's contain read/write memory (RAM), programmable read-only memory (PROM), parallel and serial input/output lines and a real-time clock (Fig. 1), so the user just adds a power supply and a terminal, avoiding the high cost of building a special-purpose microcomputer. An objective of Control Basic is to let control programs be developed and tested on the same SBC as in the final product.
127
The language contains a sub-set of the wellknown BASIC languages for numerical work, (Li-Chen Wang, 1976) with extensions suitable for many control applications (National Semiconductor, 1979) including sequence control and DDC. As sequence control generally implies operations based on Boolean variables (such as describing the state of external switch contacts), Control Basic has logical operators and can deal with individual bits of expressions. In DDC, control calculations are initiated at prescribed intervals of time; for this Control Basic allows 'background' and 'foreground' program sections to coexist, and as the interpreter routines (such as for floating-point calculations) are re-entrant, a background/foreground program can be written entirely in Control Basic. Process microcomputers have a variety of special-purpose peripherals controlled by 'programmable input/output' devices whose addresses and functions vary widely. It is necessary, therefore, to exchange binary information with devices at known absolute addresses. This is catered for by allowing constants to be defined in several radices and having constructs which define the value of an expression to be a pointer to memory or device locations. As Control Basic is interpretive, the execu-
tion speed of typical programs can be considerably slower than their machine-code counterparts, though this is often not an important factor in process-control applications. In the floating-point implementation, the overhead due to interpretation is small compared with the timings of the floating-point routines. For time-critical sections, however, 'user-routines' written in machine-code can be
D. W. Clarke
128
accessed; these are generally pre-assenbled and stored in fixed locations in PROM. These routines can themselves access various utility routines within the Control Basic interpreter. Although an outline of the syntax of Control Basic are given below, it is useful here to demonstrate the flavour of the language by the simple example of Table 1. TABLE 1
Here ex 1 is an expression giving the maximum subscript of array A, which allocates space to A(O} ....• A(ex I}; ex 2 specifies the maximum subscript of array B, etc; a value of -1 indicating no allocation. The array space can be allocated dynamically. An element of an array can be referenced by A(subscript} where 'subscript' is a general expression, and an array element can appear anywhere in an expression just as an ordinary variable.
A Small Control Basic Program
10
I = HEX E4: Q = HEX E6; input and output port addresses 20 A = IN(I}: IF A(4) = 0 THEN GOTO 20; is switch 4 on? 30 OUT (Q, BIN Ill); if so, turn on 3 lamps 40 El; enable interrupts and set reserved word COUNT to 0 SO IF IN(I} (4) <> THEN GOTO SO; switch 4 s till on? 60 OUT (Q,O); turn lamps off 70 IF COUNT < 200 THEN STOP; stop if insufficient on-time (given by COUNT) 80 GOTO 20; else repeat 32767 PRINT 'ERROR DETECTED': STOP; error trap line. The purpose of this program is to define peripheral addresses (line 10), detect whether a switch associated with a bit in an input port has been turned on, to turn on lamps connected to an output port, and to count the time that the switch has been in the on-position. Note that multiple-statement lines are allowed. SOME DETAILS OF THE LANGUAGE Numbers are stored in floating-point binary form in which 3 bytes are used for each value: 7 bits are used for the exponent and 16 bits for the fractional part, hence giving a range of about ±10-19 to 10 19 and about 4 - 5 decimal digits of precision. This format was chosen to optimize calculations using internal 8080 registers so that most operations take only 0.1 to 0.5 ms the speed and moderate accuracy is acceptable in process control. Constants are specified in jecimal by default using either integer (1, -23 .....• ), decimal (-1.3, 27.2 ..... ) or exponent form (lE2, 0.3E-6 ...... ). To use other radices the prefixes BIN (binary) OCT (octal) and HEX (hexadecimal) are used. The corresponding values are converted to their equivalent floating point representation. There are 26 ordinary floating-point variables denoted by the letters A to Z which can take on values in the valid floating-point range, and which are stored in fixed contiguous locations indicated by a pointer in the communications area. A further continguous area is allocated to array space, and up to 26 distinct arrays denoted by A(.) to Z(.) can share this area according to a DIM statement of the following form: DIM (ex 1, ex 2,
ex n)
If a and b are expressions, the arithmetic operations are the usual a+b, a-b, a*b and a/b whilst the relational operators are a>b, ab, a>=b, a<=b. The relational operators return the values of 0 (FALSE) and -1 (alII's in binary: TRUE) and can appear in more general expressions. The logical operators are ~ (NOT), & (AND), ! (OR), I (exclusive OR). Logical operators perform bit-wise operations on 16-bit values, and are executed in the following way: the expressions are evaluated and converted to equivalent l6-bit integers, the logical operations are performed and the result reconverted to floating-point form. For example: BIN 1000 ! BIN 10 produces 1010 in binary; when used with relational operators ~ (2 = 2) returns 0 (FALSE) and (2 = 2) & (3 = 3) returns -1 (TRUE). An expression E surrounded by square brackets IEl is used to signify a bit-position after the corresponding value has been converted to a 16-bit integer. The bit-positions are in the range 0 (least-significant) to IS (mostsignificant). An expression e can be followed by a bit-position locator [El, and the two together elEl give a value of 1 of the relevant bit of e is SET and 0 if it is CLEAR. This is of value when allocating significance to individual bits, such as with data corresponding to a set of switch contacts. An expression is a combination of numbers, variables, subscripted variables, functions (there are the usual Basic functions such as SIN, SQR, RND etc.), bit-values, operations and expressions following the normal rules of algebra. Expressions are generally evaluated from left to right, though there are the usual simple precedence rules, and matching brackets '(.)' can be employed to override the normal order of evaluation. A variable, array element or a bit-position may be given the value of an expression using an assignment statement of the form LET. = e; the ke)w'ord LET is optional. For example A(el) [e2) = e3 affects the el'th bit of array element A(e2} by the value of e3, so that A(22} (4) = 1 sets bit 4 of element 22 of array A to 1. The language contains the usual range of BASIC program control keywords (GOTO; GOSUB .. •••• RETURN; FOR ••... TO ..... STEP and NEXT; IF ••..• THEN; STOP) but with the following minor but useful modifications: a) the target line-number of a GOTO or GOSUB can be an expression; this is of value when using Control Basic to supervise multiple sequences;
A Simple Control Language b) the expressions associated with FOR TO .•. STEP are evaluated as integers to maximise speed; c) compound statements such as IF .... THEN IF ..... THEN etc. are allowed. Alphanumerical data can be exchanged with a terminal using PRINT or INPUT statements in the usual manner. There are primitive string functions in Control Basic (e.g. concatenation), and strings can be inputted into string variables using, for example, INPUT#A; space precludes further discussion. Byte data is transferred to a specified ouput port by an OUT ( ... ) statement and from a specified input port by an IN(.) function, where the port addressing is based on the corresponding 8080 IN and OUT machine-code commands. In each case, the least-significant byte of an expression or variable is transmitted. In view of their utility for user control of the operation of Control Basic (such as in modifying pointers), there are several mechanisms provided for communicating data with known absolute store locations. Although the common statement POKE (.,.), and function PEEK (.) are provided, it was found that these were inadequate, so the symbols %, @ and were reserved to indicate 3-byte (floatingpoint), 2-byte (integer), and byte pointers to absolute locations. The value of the associated expression is deemed to be the (first) address of the corresponding data transfer; absolute-store locators can form part of more complex expressions as well as targets of assignment statements, for example: 1'HEX 1000 [2] = 1 sets bit 2 of location 1000 (hexadecimal) A = S * % 300 A becomes S times the floatingpoint data at 300 ... 302 t A = l' A & BIN 100 mask bi t of location whose address is in A One application is to memory-mapped input/ output in which peripheral devices are addressed as RAM; a further useful feature is the ability to manipulate, for example, data corresponding to the digitized elements of a camera picture in known blocks of memory. It is often useful to access a machine-code routine either for convenience or execution speed. This is achieved by the Control Basic statement USR el, (VI, v2 ..... v n ), where el is an expression giving the starting address of the 'user subroutine' and vI'" vn are variables forming the arguments of the routine and whose addresses are transmitted on the stack. It may be considered inconvenient to access such routines only at known addresses; in practice, however, it is usual to create a set of utility procedures (such as for graphical output) and to store them in PROM. REAL TIME FEATURES A typical SBC contains a real-time clock which can be programmed to interrupt the processor at intervals. For control applications this clock
129
is used to synchronise the program with the external process. For example, in sequence control time ~ delays are necessary after certain switching operations whilst in DDC the feedback control calculations need to ~e performed at prescribed sample instants. DI (disable interrupts) and El (enable interrupts) are statements provided for simple interrupt control. El also causes the reserved variable COUNT to be cleared; COUNT is incremented by 1 on each interrupt and serves as an elementary 'time-of-day' clock. WAIT (el) is a statement used to halt execution of the program until the number of interrupts given by expression el have arrived. In background/foreground operation the interrupt causes a forced branch from the background part of the program so that the foreground part can be executed. At the end of the foreground part, the background is resumed with no effect on the calculations except for the corresponding loss of time. The start and end of the foreground section are specified by the user in his program, using SCHED (schedule), and RTI (return from interrupt) statements: SCHED (el, e2) (executed in background to point to foreground) RTI (indicating end of foreground) Expression el gives the number of interrupts between foreground schedules, and expression e2 gives the line-number starting the foreground section. For example: 100 SCHED (10, 1000); goto 1000 every 10 interrupts 1000; ; start of foreground . 1500 RTI ; end of foreground The operation is similar to GOSUB ... RETURN, except that the GOSUB is caused by the external interrupt and that only one foreground section is valid at any instant, with no further nesting of interrupts allowed. This is sufficient, however, for many DDC programs in which the background is used for operator communications and data display. A convenient application of SCHED in program development inserts a STOP statement after the SCHED so that Control Basic enters immediate mode. As with other versions of BASIC, immediate mode allows the user to enter commands or immmediately-executed statements via the terminal. Hence variables can be inspected (e.g. PRINT 1) or modified (e.g. A12] =0) whilst the foreground is still running. This method was particularly valuable in the selftuning applications.
As an example of the use of Control Basic for simple DDC loops, Table 2 outlines of a pro-
D. W. Clarke
130
gram in which 3 foreground sections are successively scheduled, one being a positional 3-term algorithm for controlling K loops. The other foreground sections could, for example, be used for sequence control and interprocess cOlIllDunication. TABLE 2
A Simple DDC Example
initialisation. K set to number of loops 50 DIM (K,K,K,K,K,-l,-l,-l,-K,-l,-l,K,K) 51 AB C DE F G H I J KL M space allocated for arrays A,B,C,D,E,I, 52 L,M 100 SCHED (10, 1000) interrupts
off to 1000 every 10
200 FOR J = 1 TO K: I(J) integrators 210 F = 2000: L = 1: El
0: NEXT J; clear ini tialise. and go
background section; e.g. operator communication 1000 GOSUB F ; branch to 2000, 3000, 4000 according to F 1010 F = F + 1000: IF F > 4000 THEN F = 1000 point to next foreground section 1020 RTI ; return to background 2000 2010 2020 2030 2040 2050 2060 2070 2080 2090 2100 2110
3-term controller on loop given by L USR HEX 32F, (L,Y) ; monitor's ADC routine L'th channel data to Y E=D(L)-Y:P=A(L)*E ; error (D(L) = desired value) proportional term I=I(L)+B(L)*E ; integral term D=C(L)*(E-E(L» : E(L)=E ; derivative term U = P+I+D ; PID IF U>M(L) THEN U=M(L) ; clip maximum U IF UK THEN L=l ; point to DDC loop RETURN; back to 'foreground executive' line 1010.
ASPECTS OF THE IMPLEMENTATION A primary objective of Control Basic is to minimise the space required by the interpreter, one with the features described above requiring only 5K bytes of PROM and an integer-only version with restricted features taking about 3K bytes. So that a range of interpreters with the distinct address spaces and other characteristics of typical SBC s ystems can be provided, the source code of Control Basic is conditionally assembled on a host computer (DEC PDP 11, VAX 11 or Intel MDS). Typical choices of the user is whether to have an integer-only or a floating point version, and one which can support IS IS or CP/M floppy-disc operating system and data
files or not (space precludes discussion of file support - data can be transmitted through INPUT or PRINT statements via channels allocated to prespecified disc files, and programs can be transmitted using READ, SAVE and OVERLAY cOlIllDands). Each interpreter has a 'colIllDunications area' at start of its PROM containing the following entries: 1) A jump instruction to the 'power-up' entry point. On entry Control Basic is initialised and either awaits user cOlIllDands from the terminal (a 'development' system) or immediately starts the user's program at the first line (a 'run-time' system). 2) A jump instruction to the 'power-fail restart' entry point, which causes the line whose number is in registers to be executed. This allows the user to deal with possible plant conditions following restoration of power after a failure. 3) A value indicating either a run-time or a development system. 4) A value indicating whether CTRL/Z entered from the terminal can halt the program. 5) A set of pointers to the addresses of the RAM communications area, the input text buffer limits and the stack limits. The next part of the PROM is copied into RAM to form the initial contents of the RAM communications area. As such, values can be modified either by the interpreter or by the user's program with direct store access statements. 6) A byte (the 'error word') in which individual bits signify particular run-time errors (e.g. floating-point overflow). 7) A byte ( the 'error mask') where clear bits indicate that the corresponding errors are to be ignored. 8) A set of pointers to the ordinary variables area (72 bytes for the letters A-Z) , the program text area limits, and the array area limits. The final part of the PROM cOlIllDunications contains a jump-table for utility (mostly floating-point) routines and for interrupt entry points (real-time clock and interrupt driven terminal handling). The user's program is stored in its text form except that keywords (LET, PRINT etc.) are converted to single-byte 'tokens' to minimise storage space and improve execution speed. The use of text means that programs are inherently relocatab1e and can therefore be stored in PROM after test in an arbitrary contiguous area provided that the associated pointers are modified; more than one such program can be stored. A set of benchmarks (Personal Computer World, 1979) has been proposed to evaluate BASIC interpreters. Though concentrating only on
A Simple Control Language numerical applications, and being rather trivial, they do indicate the speed of Control Basic compared with other interpreters operating on other systems, as shown in Table 3. TABLE 3
Some Benchmark Times
Machine/BASIC IBM 370/115 Eclipse PET 2001 IBM 5100
CCUL Rl.2 RDOS Resident Resident
Z80
Control Basic
Benchmark times 1.3 0.5 1.7 4.5
1.4 1.8 9.9 21.1
2.3 4.3 18.4 57.4
1.9 5.0 20.4 54.5
2.1 5.1 21. 7 59.0
3.1 9.0 32.5 88.2
4.6 13.0 50.9 174.9
1.0
7.0
10.0
12.0
14.0
25.0
38.0
SOME APPLICATIONS Although Control Basic has been used in industrial control, described below are applications to education and research at Oxford University. In the educational exercises tested programs are stored in PROM, whilst in the research projects floppy discs store programs and data acquired on-line. The first application consists of data collection from a 4-cylinder petrol engine used for thermodynamics experiments, as shown in Fig. 2. The objective of the program is to plot and integrate the pressure/volume diagram (indicator diagram) using transducers connected to each cylinder. By averaging the P-V data over several cycles a smooth diagram is obtained, which can then be plotted at slow speed using D/A converters, and whose area gives the work done per cycle. In view of the speed of the engine, a USR had to be written so that data can be acquired at a fast enough rate. A similar system is used on a reciprocating air compressor. The second application to education consists of the testing of the Kapl'a n turbine shown in Fig. 3 to obtain performance charact:ristics in terms of dimensionless numbers WhlCh could then be used to predict the behaviour of a full-size turbine. There are too many measurements for a manual experiment, but using the microcomputer to take and analyse readings . directly means that a greater range of condltions (e.g. changes in the angle of the inle~ guide vanes ) can be studies in the time avallable. As before, a set of readings is averaged to get smoothed values, the acquisition of data now being scheduled at ls intervals so that Control Basic statements rather than machine-code routines can be used to control the A/D converters. In this system the Control Basic program in PROM can be transferred to RAM so that the students can easily add to the program for further data analysis; such a
131
facility is used in the Control Systems laboratory in which a portable microcomputer can be programmed by the students based on a provided PID prototype algorithm. In injection moulding of plastic components the machine passes through a simple sequence (dies close, melt injection, dwell for forming, plunger return, dwell for cooling, dies open, eject, dwell) such that the quality of the final component depends on the speeds and timings of the various operatio~s. The machine is actuated by a set of solenolds and monitored via a set of interlocks and limit switches, with possibly elementary closed-loop control of melt temperature. As a student project, a Control Basic program (Wright, 1979) was written in which the machine and the thermodynamic behaviour of the plastic was simulated with the intention later of coupling the microcomputer to a real injection moulder. The objective of the controller was to optimise throughput and quality by adjusting speeds, pressures and temperatures and this was achieved by simply incrementing or decrementing their values by given amounts according to appropr~ate measures during the cycle. Operator lnformation was displayed using bar-graphs for variables and flags showing the states of solenoids and limit-switches. A random number generator was used to stimulate errors (e.g. solenoid failure) to test for correctly programmed recovery procedures. The simulation worked well, as did the hill-climbing control algorithm - provided that the initial values were reasonably close to their ideal. Research into self-tuning control (Clarke and Gawthrop, 1981) has been one of the main motivations for developing Control Basic, as a portable control system could then be used to implement self-tuning at remote industrial sites. It was invariable found that special coding, such as for sequencing or for providing cascaded PID control, was required before a self-tuner could be placed in a loop, and the straightforward modifiability of a Control Basic program has proved to be most useful. A self-tuning algorithm is scheduled as a foreground task, with Control Basic acting in immediate mode in the background to allow for simple interaction by the user with the associated variables. In its most recent form (Fig. 4), the terminal provides graphical output and the sequencing of the self-tuner is controlled by 8 push-buttcns (e.g. for switching estimation, data logging, selftuning and back-up PID control, etc). This means that the self-tuner can be monitored by the normal process operator in an extended experiment that is under way to see whether special skills are required to employ an adaptive control law in industry compared with traditional PID methods. This application involves most of the interesting features of Control Basic: realtime operation, bit-manipulation (for handling the push-buttons), disc-file support
D. W. Clarke
132
(for data logging), USR's (for graphical output, data filtering and parameter estimation), direct-store access (for manipulating pointers to indicate different prior data-bases) and control of peripheral devices. The restricted accuracy has not proved to be a handicap as care was taken to use numerically sound recursive parameter updating.
REFERENCES Clarke, D. W. (1980). OUEL/WSL Control Basic. Report, Oxford University. Clarke ', D. W. and Gawthrop, P.J. (1981). Implementation and application of microprocessor self-tuners. Automatica, 17, pp. 233-244. Li -Chen Wang (1976). Palo Alto Tiny Basic. Dr. Dobbs Journal, l.
CONCLUSION The paper has decribed a straight-forward cheap language for process control applications. Though the syntax does not reflect current ideas of structured programming, the language and its implementation have proved to be successful and popular for real-time applications where there is close coupling between the microcomputer and its environment.
National Semiconductor Corp. (1979). NIBL reference guide. Personal Computer World. (1978). mark tests, l.
SC/MP
BASIC bench-
Wright, S. (1979). Simulation and control of an injection moulding machine. Report, Oxford University.
ACKNOWLEDGEMENTS I would like to thank Mrs. P. J. Frost for her work in coding the Control Basic interpreters, and Warren Spring Laboratory for providing financial support for later versions.
Peripheral devices PROM
CPU
RAM
Bus to
~
other SBC's ~ Pressure
Real - time clock Displacement
Fig. 1
Fig. 2
A single-board computer
Engine test-bed experiment
Load cells Graphical output Program modification Flow
4 ____ GUide vane angle
~
Controlled
.~
Process
Buttons Lights Operator Interface
Fig. 4 Fig. 3
The Kaplan turbine experiment
A portable adaptive control system