A Tutorial Introduction To HPIB

v4.1 / 01 jan 99 / greg_goebel / public domain / hpib_tutorial

* This document is a tutorial introduction to the HPIB interface, covering theory and use of the HPIB from fundamental specs to instrument programming and HPIB card configuration.


Table Of Contents

[1.0] HPIB Tutor (1): Introduction

[2.0] HPIB Tutor (2): HPIB 488.1 / HPIB Fundamentals

[3.0] HPIB Tutor (3): IEEE 488.2 -- Overview & Data Formats

[4.0] HPIB Tutor (4): 488.2 Common Commands & Status

[5.0] HPIB Tutor (5): Introduction To SCPI

[6.0] HPIB Tutor (6): A SCPI-Based HPIB Instrument -- The 34401 DMM

[7.0] HPIB Tutor (7): Notes & Comments


[1.0] HPIB Tutor (1): Introduction

* This section provides a tutorial overview of the Hewlett-Packard Interface Bus (HPIB) interface system, also known as the General-Purpose Interface Bus (GPIB) or by its Institute of Electrical and Electronic Engineers (IEEE) specification number, IEEE-488. HPIB is a scheme by which groups of devices may be connected to a controlling computer and communicate under its direction. It is highly standardized and instruments from multiple vendors can be operated in the same HPIB system.

The HPIB standard is defined at several levels:

This document is divided into modules to discuss the following topics:

There are plenty of source materials available for these topics and I have made full use of them. Materials on 488.1 and 488.2 are derived from the HP publication A TUTORIAL DESCRIPTION OF THE HEWLETT-PACKARD INTERFACE BUS, while the SCPI material is derived from Barry Eppler's A BEGINNER'S GUIDE TO SCPI. Of course, the section on the ALF draws heavily on the 34401A manual.

This document requires a knowledge of fundamental computer concepts and nomenclature. A small knowledge of electronics technology is also useful. Little other knowledge is assumed.

* If you are using this document for self-study rather than reference, a few guidelines should help you make the best use of it:

* I wrote this document out of a sense of frustration. HPIB has been a core concern of my work for many years, but at the same time I never really felt like I understood the topic through its full spectrum, in the proper balance between minor details and broad application.

The fact that there was no document available that described HPIB all the way from the fundamental definitions up to implementations led me to want to write one myself. I wanted to not only ensure that I did in fact have an understanding of that full range, but also to spare others the roundabout path I took to get there.

The first major version was basically a ripoff of the source materials. The second major version was a complete rewrite and reorganization of the first (that started out, ironically, as an attempt to correct a single typographic error and got remarkably out of hand).

The second version is far superior to the first since it focuses on practical concepts rather than some of the (sometimes bewildering and excessive) theory devised to support the 488.2 and (in particular) SCPI specs.

While this document is necessarily terse -- it covers a very wide range of material -- you should find it informative and (if you can get into this sort of thing) even entertaining.

* Some of the intermediate versions of this tutorial included materials on actual programming interfaces for HPIB, and how to configure PC HPIB and GPIB cards for the PC. For various reasons, this turned out to be a clumsy organization, and so those intermediate versions evolved into three independent document: this tutorial overview; a document on programming interfaces; and a document on HPIB card configuration.


[2.0] HPIB Tutor (2): HPIB 488.1 / HPIB Fundamentals

* This module provides an overview of the fundamental HPIB specification, IEEE 488.1



BACK TO INDEX

[2.1] 488.1 OVERVIEW

* The Hewlett-Packard Interface Bus (HPIB) is a strictly-defined general-purpose computer interface system, in effect an external computer bus that allows interconnection of instruments and other devices to a controlling computer. General specifications of HPIB include:

Investigations for an interface system that led to the HPIB spec began in 1965, and eventually resulted in the first HPIB spec, now designated IEEE 488.1-1975. Further work and investigations led to the additional spec for common commands and data formats, designated IEEE-488.2-1987.

There are other specifications related to IEEE-488.1. The ANSI MC1.1 spec provides a definition identical to 488.1. The IEC 625-1 and BS 6146 standards are the same as 488.1, except that they provide interconnections through a 25-pin subminiature "D" connection, identical to that used on serial (RS-232) interfaces. These IEC and BS standards are very little used.

The 488.1 and related specifications cover the logical, electrical, and mechanical specs of the HPIB system. The 488.2 spec extends this definition to provide a small set of common instrument commands and specifications for data to be sent over the HPIB. A further new specification, known as SCPI (Standard Commands for Programmable Instrumentation), defines instrument command sets for use over HPIB or other interfaces. 488.2 and SCPI are discussed in later modules in this series.

* The key specifications of IEEE 488.1 are listed below:

[2.2] HPIB FUNCTIONS & CAPABILITIES

* The operation of the HPIB can be compared to that of a committee. A committee chairman controls which member talks and implies that the others should listen. IEEE 488.1 has one device that controls, deciding who talks and who listens (under normal circumstances the controlling device will be one half of the conversation, but it doesn't have to be). Every IEEE 488.1 device must be capable of performing one or more of the following interface functions:

The IEEE 488.1 spec defines these functions in (agonizingly) concise terms using abstract state machines labeled with rigorously-defined nomenclature. These functions are referred to as interface capabilities.

There are other interface capabilities besides Listener, Talker, or Controller, which are also defined in the 488.1 spec as state machines. These functions are listed below, along with their abbreviations:

The IEEE 488.1 spec also defines subsets of these functions, given by a number appended to the function code. The spec recommends that each device be marked near its connector with the interface capability codes for the functions the device supports.

For example, a device with:


   Talk capability.
   The ability to send status bytes.
   Listen capability.
   A Listen-only mode switch.
   Service request capability.
   Full remote-local capability without local lockout.
   Local configuration of the parallel poll capability.
   Complete device clear capability.
   No capability for device trigger.
   No Controller capability.

-- would be identified with these codes:


   SH1  AH1  T6  L3  SR1  RL2  PP2  DC1  DT0  C0  E1

A full description of the IEEE 488.1 spec's discussion of these capabilities is far beyond the scope of this document, and is in fact generally only useful for design engineers building HPIB devices.

[2.3] HPIB SIGNAL LINES & COMMANDS

* The physical interconnection system used in HPIB uses a shared-bus structure, with 16 signal lines and 8 ground lines. The bus signal lines all use a low-true logic convention, and can be grouped into 3 sets:

The organization of the signal lines is shown below:


   DIO1 ---------------------------------  -+
   DIO2 ---------------------------------   |
   DIO3 ---------------------------------   |
   DIO4 ---------------------------------   | data lines
   DIO5 ---------------------------------   |
   DIO6 ---------------------------------   |
   DIO7 ---------------------------------   |
   DIO8 ---------------------------------  -+
 
   NDAC ---------------------------------  -+
   NRFD ---------------------------------   | handshake lines
    DAV ---------------------------------  -+

    EOI ---------------------------------  -+
    REN ---------------------------------   |
    SRQ ---------------------------------   | general bus management lines
    ATN ---------------------------------   |
    IFC ---------------------------------  -+

The signal lines use TTL voltage levels. The pinouts are as follows:


                                            * 
                                       *      * 
                                  *           *
                  SIGNAL GROUND   * [24] [12] *   SHIELD (to earth ground)
   twisted-pair ground with ATN   * [23] [11] *   ATN
   twisted-pair ground with SRQ   * [22] [10] *   SRQ
   twisted-pair ground with IFC   * [21] [ 9] *   IFC
   twisted-pair ground with NDAC  * [20] [ 8] *   NDAC
   twisted-pair ground with NRFD  * [19] [ 7] *   NRFD
   twisted-pair ground with DAV   * [18] [ 6] *   DAV
                            REN   * [17] [ 5] *   EOI
                           DIO8   * [16] [ 4] *   DIO4
                           DIO7   * [15] [ 3] *   DIO3
                           DIO6   * [14] [ 2] *   DIO2
                           DIO5   * [13] [ 1] *   DIO1
                                  *           *
                                       *      *
                                            * 

The data lines allow information transfer a byte at a time. Device commands and data are often transferred as strings of ASCII characters for ease of use, while large blocks of data are often transferred as binary data for speed and compactness. The data lines are also used by the HPIB protocol to send HPIB interface commands and addresses as bytes.

The three handshake lines are used to transfer bytes over the data lines from a source (an addressed Talker or an Active Controller) to an acceptor (an addressed Listener or all devices receiving interface commands). The byte transfer controlled by the handshake lines allows more than one device to accept bytes simultaneously, and is "asynchronous": that is, the rate of byte transfer is determined both by the source and acceptor(s), and can in principle take as long as necessary. When there are multiple acceptors, the byte transfer will take place at the speed of the slowest one.

The three handshake lines are defined as follows:

The low-true logic of the handshake lines can be confusing. The protocol can be outlined as follows:


   1:  NRFD HIGH   All acceptors ready for byte.
   2:  DAV LOW     Source says byte is valid ...
   3:  NRFD LOW    ... so acceptors drop NRFD line.
   4:  NDAC HIGH   All acceptors have accepted byte ...
   5:  DAV HIGH    ... so source raises DAV line ...
   6:  NDAC LOW    ... and acceptors drop NDAC line.
   1:  NRFD HIGH   All acceptors ready for next byte, cycle begins again.
 

Neither NRFD nor NDAC will go high unless all acceptors make them high. This allows the speed of the byte transfer to be controlled by the slowest acceptor. all

The following illustration shows the handshake in a different way:


      +---------------------------------------------------------------+
      |                                                               |
      |             .......................               ........... |
 byte | ............                       ...............            |
      |             .......................               ........... |
      |                                                               |
      | ..............                   ....................         |
 DAV  |              :                   :                  :         |
      |              :...................:                  :........ |
      |                                                               |
      |       ...........                            ...........      |
 NRFD |       : : :     :                            : : :     :      |
      | ......:.:.:     :............................:.:.:     :..... |
      |                                                               |
      |                           ...........                         |
 NDAC |                           : : :     :                         |
      | ..........................:.:.:     :........................ |
      |                                                               |
      +-----------+--+--+-------------+--+--+------------+--+--+------+
                  |  |  |             |  |  |            |  |  |
                  1  2  3             4  5  6            1  2  3
 

* The five general bus management lines are used to manage the orderly flow of information over the HPIB:

The signal lines are driven either by open-collector or tristate drivers. Maximum data rate is 250 kilobytes per second for open-collector drivers and 1 megabyte per second for tristate drivers.

The connector for the HPIB cable allows connectors to be stacked on top of each other, to allow for daisy-chained or star connections (though the stack grows clumsy above three levels of stacking). Some specialized HPIB cables (such as those often used on personal computers, where access to I/O cards is mechanically restricted) may have a connector that does not permit stacking.

* Note the important distinction between the operation of the HPIB when ATN is asserted and when it is released. When ATN is asserted by the Active Controller, the HPIB is in Command Mode: the Active Controller configures the HPIB or performs other control tasks. When ATN is released, the HPIB is in data mode: the addressed Talker sends bytes to the addressed Listeners.

In Command Mode, the Active Controller sends four classes of commands:

In data mode (ATN released), device-dependent data (device programming command bytes, measurement data bytes, and status bytes) is transferred from the addressed Talker to the addressed Listeners. Only the addressed Listeners actually handshake the byte.

The actual format for the device-dependent data is beyond the scope of the 488.1 spec. It can, and does, have any format desired by the device manufacturers. The 488.2 and SCPI specs have made substantial progress in clearing up this chaotic situation, however.

* Most common operations on an HPIB consist of byte transfers between an addressed Talker and addressed Listener(s), as well as capabilities to clear devices either singly or universally, and trigger them to perform some device-dependent function. The signal lines and command set, as described above, also support some other functionality:

The addressing scheme and command bytes are discussed in more detail in the following sections.

[2.4] HPIB ADDRESSING

* Every 488.1 device has at least one Talk and Listen address (with the exception of freak antique devices that only Talk or Listen). A device's address is normally set at the factory, but can traditionally be changed (in older devices) by adjusting a set of DIP switches or (in more modern instruments) with front-panel inputs. Many devices display their HPIB address on power-up.

If the device has DIP switches, they are usually arranged as follows:


       1    2    4    8   16
   +---------------------------+
   |  +-+  +-+  +-+  +-+  +-+  | 1
   |  |X|  | |  |X|  | |  | |  |
   |  | |  |X|  | |  |X|  |X|  |
   |  +-+  +-+  +-+  +-+  +-+  | 0
   +---------------------------+
       A1   A2   A3   A4   A5
 

This switch setting gives an address of 5. In nearly all cases an instrument has the same Talk and Listen address. The 488.1 spec allows them to be different, but in practice that is a useless complexity. Most modern instruments allow the user to press a button to display the current HPIB address to eliminate the need to turn the instrument around and figure out the switch settings.

The switch settings allow the device to be set to Talk/Listen addresses from 0 to 30. The Listen address bytes are defined by adding a decimal value of 32 to the address, while the Talk address bytes are defined by adding a decimal value of 64 to the address. For the example given by the switch settings above, this gives the following address bytes:


   Listen address 5 = 32 + 5 = 37 decimal = 001 00101 binary
   Talk address 5 =   64 + 5 = 69 decimal = 010 00101 binary
 

The Talk and Listen address bytes are often referred to in documentation by the mnemonics TAD (Talk ADdress) and LAD (Listen ADdress). The full range of Talk addresses is therefore given by TAD0 through TAD30, and the full range of Listen addresses is given by LAD0 through LAD30.

Remember that a Controller also has a Talk and Listen address to allow it to transfer bytes in data mode to other devices on the HPIB. 21 and 30 are common Controller Talk / Listen addresses in HP equipment, though it can be any address. Note that adding a device with the same address as the Controller is a common error, and can lead to baffling problems.

The Controller's Talk and Listen address are often referred to as MTA (My Talk Address) and MLA (My Listen Address) for convenience, but there's no difference between the address format used by the Controller and by devices. Note that the Controller has to send the address bytes even when it is addressing itself!

Note also that the address switches can physically be set to a value of 31, but that is not a valid HPIB address! The address byte that has the value 32 + 31 = 63 decimal is not LAD31, it's a special address byte called Unlisten (UNL), which tells the currently addressed Listeners to stop being Listeners, usually preparatory to addressing new Listeners.

Similarly, the address byte that has the value 64 + 31 = 95 decimal is not TAD31, it's a special address byte called Untalk (UNT), which tells the currently addressed Talker to stop being a Talker, usually preparatory to assigning a new Talker.

Actually Untalk is a little redundant, since sending out a new TAD will automatically Untalk the current Talker -- as there can be only one Talker at a time.

* As noted, the 488.1 spec allows the 31-address limit to be extended to 961 addresses with a "secondary address" byte. This byte is sent after a LAD or TAD byte and consists of the decimal value 96 added to an address in the range of 0 through 30. This secondary address byte is referred by the mnemonic SC, giving the secondary address bytes SC0 through SC31.

There is no secondary address 31, even though that byte is not otherwise used. Apparently this convention was specified for consistency with the primary Talk/Listen address bytes.

Secondary addresses are not normally used to allow addressing of more devices on the HPIB. As noted, the HPIB cannot accommodate more than 15 instruments under normal conditions, and the idea of a system having anywhere near 961 devices is hard to take seriously. It is more often used to allow individual access to different modules in a modular instrument system, such as a VXI mainframe or data-acquisition box, which in either case consist of a chassis containing multiple plug-in cards that perform separate functions.

There are modular devices in which different modules are selected by sending a high-level command to the mainframe in which they are plugged. Such schemes are not standardized and vary widely, but are collectively referred to as "subaddressing", if only as a term of convenience. Please take care when programming a modular instrument to determine if the instrument supports secondary addressing or subaddressing.

[2.5] HPIB COMMANDS

* The five universal multiline (byte) commands are, as noted, accepted by all devices on the HPIB. The commands consist of:

* The four complementary uniline universal commands consist of the three general bus managements lines IFC, REN, and ATN executing their normal functions, plus the combination of EOI and ATN, which is used to conduct a parallel poll, as described earlier.

* The addressed command bytes are only accepted by addressed devices. Whether the devices are the Listeners or the Talkers depends on the command. The five commands are as follows:

* The two secondary commands consist the PPE (Parallel Poll Enable) and PPD (Parallel Poll Disable). Both are send to the addressed Listeners after they receive the PPC byte.

PPE actually consists of a set of commands that have the exact same values (96 plus 0 through 30) as the secondary address bytes. A PPE command byte is distinguished from the matching secondary address byte by the fact that a PPE byte follows a PPC command byte, while the secondary address byte follows a Talk or Listen address.

PPE configures the addressed Listeners that receive it to respond to a parallel poll by setting a given DIO line to a particular polarity (1 or 0). PPD tells the addressed Listeners not to respond to a parallel poll.

[2.6] HPIB IN OPERATION -- AN HP BASIC EXAMPLE

* Now that we have considered the theoretical aspects of the 488.1 specification, let's put all these details together by observing the HPIB transactions of a typical HPIB controller.

In this case, the controller is a computer running HP's measurement-oriented HP BASIC language, connected to a 34401 digital multimeter (DMM) over HPIB. The Controller's HPIB interface is designated by a one-digit number code called an "interface select code", or ISC. The default ISC is usually 7.

The DMM is set to its default HPIB address of 22. HP BASIC locates the instrument by tacking the HPIB address onto the end of the ISC, so the DMM is identified by the number 722. The controller itself in this case has a default Talk/Listen address of 30.

The following HP BASIC program clears the DMM, reads a DC voltage from it, prints it, serial-polls the DMM, and prints the results. The only reason that the serial poll is conducted is to give the program another thing to show off. There normally isn't any reason to do a serial poll after taking a measurement, though it is a simple way to determine if any gross instrument errors have occurred.


   10    REAL Rdg
   20    INTEGER Stat
   30    ASSIGN @Dmm TO 722                    ! Define DMM HPIB address.
   40    CLEAR 7                               ! Clear HPIB interface.
   50    OUTPUT @Dmm;"*RST"                    ! Reset DMM. 
   60    OUTPUT @Dmm;"*CLS"                    ! Clear DMM.
   70    OUTPUT @Dmm;"MEASURE:VOLTAGE:DC? DEF" ! Measure DC voltage.
   80    ENTER @Dmm;Rdg                        ! Get value back.
   90    PRINT "Reading Value:      ";Rdg      ! Print it.
   100   Stat=SPOLL(@Dmm)                      ! Serial poll DMM.
   110   PRINT "Serial Poll status: ";Stat     ! Print status value.
   120   END
 

Let's take a look at the statements in the program in detail.

* The first three lines simply declare variables. "Rdg" is a REAL variable used to store the voltage reading; "Stat" is an INTEGER variable used to store the status byte returned by the serial poll; and "@Dmm" is an "I/O path" or "I/O handle" that stores the device address of 722.

The statement:


   CLEAR 7

-- simply clears all the devices on the HPIB, though there's only one in this case. The HPIB operations performed are as follows:


   REN  ATN      : DCL
 

This table and the ones that follow give the byte(s) transferred by the HP BASIC statement and the status of the bus-management lines. The 3-wire handshake is implied in each byte transfer, and so will not be mentioned. Just remember that each line in a table defines a single byte transfer using the 3-wire handshake.

The right side of the table gives the byte transferred. In this case it is the universal command byte, DCL, or Device CLear, which clears the interfaces of the instruments on the HPIB.

The left side of this table gives the status of the three control lines REN, ATN, and EOI. SRQ and IFC are always inactive in this sequence of examples, so they won't be shown. REN and ATN are active, indicating a command byte, so they are shown. EOI is inactive and is not shown.

The next statement is:


   OUTPUT @Dmm;"*RST"
 

The OUTPUT statement is used by HP BASIC to send bytes over the HPIB to the remote device, the DMM. In this example, the following bytes are sent:


   REN  ATN      : TAD30 (MTA)
   REN  ATN      : UNL
   REN  ATN      : LAD22
   REN           : "*"
   REN           : "R"
   REN           : "S"
   REN           : "T"
   REN           : CR
   REN           : LF
 

The first three bytes are sent to set up the Controller as a Talker and the DMM as a Listener, and then the ASCII string "*RST" (device Reset) is sent to the DMM. The string is "terminated" by the carriage-return (CR) and line-feed (LF) control characters -- that is, when the DMM receives the CR-LF, it assumes that the command is complete and acts upon it.

Note how ATN is active when sending the three HPIB command bytes, and how it is inactive when sending the instrument command string.

Another OUTPUT statement follows:


   OUTPUT @Dmm;"*CLS"
 

This performs roughly the same actions as the first OUTPUT statement but with a different string, "*CLS" (clear status):


   REN  ATN      : TAD30 (MTA)
   REN  ATN      : UNL
   REN  ATN      : LAD22
   REN           : "*"
   REN           : "C"
   REN           : "L"
   REN           : "S"
   REN           : CR
   REN           : LF
 

Note that the OUTPUT statement sends the same MTA-UNL-LAD22 addressing sequence that was sent in the previous step. In theory that is redundant -- the Controller is already the addressed Talker and the DMM is already the addressed Listener -- and in fact there is a way in HP BASIC to eliminate the addressing sequence, but in practice that is generally a useless micro-efficiency.

Note also that "*RST" and "*CLS" are "common commands" that are defined by the 488.2 spec. They will be discussed in more detail in a later chapter.

The question arises: why send these commands if we've already sent a DCL? Simple answer: DCL only resets the HPIB interface on the DMM, and returning the instrument to a completely known state requires a little more work.

The third OUTPUT statement:


   OUTPUT @Dmm;"MEASURE:VOLTAGE:DC? DEF"
 

-- sends the DMM command bytes needed to tell the DMM to read a DC voltage:


   REN  ATN      : TAD30 (MTA)
   REN  ATN      : UNL
   REN  ATN      : LAD22
   REN           : "M"
   REN           : "E"
   REN           : "A"
   REN           : "S"
   REN           : "U"
   REN           : "R"
   REN           : "E"
   REN           : ":"
   REN           : "V"
   REN           : "O"
   REN           : "L"
   REN           : "T"
   REN           : "A"
   REN           : "G"
   REN           : "E"
   REN           : ":"
   REN           : "D"
   REN           : "C"
   REN           : "?"
   REN           : " "
   REN           : "D"
   REN           : "E"
   REN           : "F"
   REN           : CR
   REN           : LF
 

Other than the string being longer, this is identical in logic to the previous two output statements. Note that the DMM command conforms to the SCPI command set, which will be discussed in detail in a later chapter. The command string's meaning in this case should be obvious, except for the "DEF" string, which specifies the DEFault voltage range for the DMM.

Now that the HP BASIC program has told the DMM to read the voltage using an OUTPUT statement, the program has to read the voltage value back, using the matching ENTER statement:


   ENTER @Dmm;Rdg
 

This performs the actions:


   REN ATN       : UNL
   REN ATN       : LAD30 (MLA)
   REN ATN       : TAD22
   REN           : "-"
   REN           : "1"
   REN           : "."
   REN           : "4"
   REN           : "5"
   REN           : "0"
   REN           : "5"
   REN           : "2"
   REN           : "0"
   REN           : "4"
   REN           : "0"
   REN           : "E"
   REN           : "+"
   REN           : "0"
   REN           : "1"
   REN       EOI : LF
 

The ENTER statement is similar to the OUTPUT statement, except that the direction of byte transfer is reversed: the Controller is the Listener and the DMM is the Talker. The DMM returns the voltage value as a string; the terminator at the end of the value is a line-feed combined with assertion of the EOI line. This particular termination scheme is defined in the 488.2 spec.

Once the program receives the voltage value back, it is printed to the computer's display with:


   PRINT "Reading Value:      ";Rdg
 

The HP BASIC program then queries the DMM for serial-poll status with:


   Stat=SPOLL(@Dmm)
 

This performs the following actions:


   REN ATN       : UNL
   REN ATN       : LAD30 (MLA)
   REN ATN       : TAD22
   REN ATN       : SPE
   REN           : 0
   REN ATN       : SPD
   REN ATN       : UNT
 

The Controller sets itself up as an addressed Listener and sets up the DMM as an addressed Talker. The Controller then send the SPE (Serial Poll Enable) command byte to tell the DMM to respond to the poll. The DMM returns a byte with the value of 0 (same as the NULL character) indicating it has nothing to report. Note that ATN is released when the poll-response byte is returned, as only the Controller can send bytes while it is asserted. ATN is then asserted again, the Controller sends the SPD (Serial Poll Disable) command byte, and then UNTalks the DMM.

* This example covers the vast majority of what is in practice done by HPIB users: it sends a command to one device and reads back a value from it, then polls the device for errors.

To be sure, this example is oversimplified, in that instruments often return large amounts of data. Sending numeric data in string format is time-consuming and clumsy, so in practice large blocks of data are sometimes sent in binary format. It would have been nice to have had the DMM assert an SRQ, but configuring the DMM to do so is too complicated for a simple example.

It is also appropriate in most cases to set an I/O timeout on a device in an HP BASIC program (using the ON TIMEOUT statement) to prevent the program from hanging if the DMM doesn't respond in the 3-wire handshake, but again, for simplicity, this was not done.

Note that in this example, there is only one addressed Talker and one addressed Listener. While the 488.1 spec does allow for multiple addressed Listeners, in practice there is usually only one. No parallel poll is performed; as noted, it is virtually never done. A pass control is not performed; this can be a complicated procedure, and the situations that require it are rare.

[2.7] HPIB IN PRACTICE

* After its introduction in the 1970s, HPIB was commonly used to interface instruments, printers and plotters, and disk drives to early personal computers and workstations. HP, not surprisingly, was strongly dedicated to HPIB and came out with a wide range of HPIB devices that were hooked up to dedicated BASIC-language workstation computers that often had built-in HPIB ports.

Over time, HPIB printers, plotters, and disk drives, as well as dedicated BASIC-language workstations, became extinct, but HPIB remained and remains important for constructing instrumentation systems, using UNIX (tm) workstations and (in particular) personal computers as Controllers. A plug-in HPIB card is used to connect the controller to a benchtop or rack of instruments; standard languages, such as C or BASIC, are generally used to direct the system.

There are a variety of different plug-in cards available from different vendors for different platforms, generally based on the Texas Instruments 9920 chip or the Nippon Electric 7210 chip. National Instruments (NI) introduced an IC of their own that can be switched to function either as the TI chip or the NEC chip, and have used it on their own HPIB cards. The different vendors' cards are not in general compatible at a hardware level.

For the most part, the HPIB cards are controlled by standard programming languages such as C or BASIC, through a special library of subprogram calls provided with the HPIB card. Traditionally, these libraries have not been compatible, either, though NI did provide a driver for Windows named GPIB.DLL that other vendors emulated.

HP devised their own standardized interface control library, named SICL (Standard Instrument Control Language), and further efforts have been made to create a "universal" interface control library that is supported by multiple vendors. This universal library has the name VISA (Virtual Instrument Standard Interface). So far, VISA has met with limited success.

The libraries are useful for writing programs to control instruments from a controller. HPIB is very well thought-out and interfacing from a controller to an instrument is easy.

However, it is much more difficult to use them to write a program that allows a computer to be used as a "device" by a separate controller, since this requires a low-level knowledge of the HPIB spec. An experienced programmer will take many months to master the specs. Similarly, multiple-controller applications are difficult to set up, and should be regarded with caution.

External HPIB interfaces are also available that plug into a parallel port. Software drivers allow such interfaces to be accessed as if they were directly plugged into the PC.

A particularly interesting new technology is the LAN-HPIB bridge, which is a small box that contains a LAN and HPIB interface and allows communications with an HPIB device over a network. With the proper software, such a LAN-HPIB bridge can be largely transparent to software, though the user has to remember that the LAN is a mutual-access interface and that latency times can be long.

HPIB bus extenders are available that allow operation of HPIB systems over long distances, using a coaxial-cable or fiber-optic link. There are also extenders that operate as modems, allowing in principle operation over any distance, but they are suspect since they don't always meet HPIB timing specs.

National Instruments has defined a "TNT" spec extension to HPIB to allow extremely high operation speeds, but such a claim should be regarded skeptically: the TNT spec will only work if the remote devices support it, and few do.

In general, maximum performance over an HPIB system is in the 100 KB to 250 KB range when performing long data transfers. In all but the most highly optimized systems, overall program operations determines the speed, not raw HPIB throughput. Specs for HPIB cards claiming much higher speeds should also be regarded skeptically: such performance figures are based on unrealistic tests, and in practice one HPIB card is just about as fast as the other.

[2.8] ASCII TABLE FOR HPIB

* The table below gives the full standard 7-bit ASCII character set and the values of each character in decimal (D), hexadecimal (H), and octal (0), along with the corresponding HPIB address or command byte (if one exists).

Note that LAD0-LAD30 is abbreviated to L0-L30, and TAD0-TAD30 is abbreviated to T0-T30. The secondary command bytes (secondary addresses and the PPE / PPD commands) are listed in the right-hand column as SC0-SC31.


  __________________________________________________________________________

  ASCII Table For HPIB                                                        
  __________________________________________________________________________

  ch ctl cmd   D  H  O ch cmd  D  H  O  ch cmd  D  H   O  ch cmd    D  H   O 
  ___________________  ________________ ________________  __________________ 

  NUL ^@      0  0  0  sp L0  32 20 40   @ T0  64 40 100   ' SC0   96 60 140 
  SOH ^A GTL  1  1  1   ! L1  33 21 41   A T1  65 41 101   a SC1   97 61 141 
  STX ^B      2  2  2   " L2  34 22 42   B T2  66 42 102   b SC2   98 62 142 
  ETX ^C      3  3  3   # L3  35 23 43   C T3  67 43 103   c SC3   99 63 143 
  EOT ^D SDC  4  4  4   $ L4  36 24 44   D T4  68 44 104   d SC4  100 64 144 
  ENQ ^E PPC  5  5  5   % L5  37 25 45   E T5  69 45 105   e SC5  101 65 145 
  ACK ^F      6  6  6   & L6  38 26 46   F T6  70 46 106   f SC6  102 66 146 
  BEL ^G      7  7  7   ` L7  39 27 47   G T7  71 47 107   g SC7  103 67 147 
  ___________________  _______________  ________________  __________________ 

  BS  ^H GET  8  8 10   ( L8  40 28 50   H T8  72 48 110   h SC8  104 68 150 
  HT  ^I TCT  9  9 11   ) L9  41 29 51   I T9  73 49 111   i SC9  105 69 151 
  LF  ^J     10  a 12   * L10 42 2a 52   J T10 74 4a 112   j SC10 106 6a 152 
  VT  ^K     11  b 13   + L11 43 2b 53   K T11 75 4b 113   k SC11 107 6b 153 
  FF  ^L     12  c 14   , L12 44 2c 54   L T12 76 4c 114   l SC12 108 6c 154 
  CR  ^M     13  d 15   - L13 45 2d 55   M T13 77 4d 115   m SC13 109 6d 155 
  SO  ^N     14  e 16   . L14 46 2e 56   N T14 78 4e 116   n SC14 110 6e 156 
  SI  ^O     15  f 17   / L15 47 2f 57   O T15 79 4f 117   o SC15 111 6f 157 
  ___________________  _______________  ________________  __________________ 

  DLE ^P     16 10 20   0 L16 48 30 60   P T16 80 50 120   p SC16 112 70 160 
  DC1 ^Q LLO 17 11 21   1 L17 49 31 61   Q T17 81 51 121   q SC17 113 71 161 
  DC2 ^R     18 12 22   2 L18 50 32 62   R T18 82 52 122   r SC18 114 72 162 
  DC3 ^S     19 13 23   3 L19 51 33 63   S T19 83 53 123   s SC19 115 73 163 
  DC4 ^T DCL 20 14 24   4 L20 52 34 64   T T20 84 54 124   t SC20 116 74 164 
  NAK ^U PPU 21 15 25   5 L21 53 35 65   U T21 85 55 125   u SC21 117 75 165 
  SYN ^V     22 16 26   6 L22 54 36 66   V T22 86 56 126   v SC22 118 76 166 
  ETB ^W     23 17 27   7 L23 55 37 67   W T23 87 57 127   w SC23 119 77 167 
  ___________________  _______________  ________________  __________________ 

  CAN ^X SPE 24 18 30   8 L24 56 38 70   X T24 88 58 130   x SC24 120 78 170 
  EM  ^Y SPD 25 19 31   9 L25 57 39 71   Y T25 89 59 131   y SC25 121 79 171 
  SUB ^Z     26 1a 32   : L26 58 3a 72   Z T26 90 5a 132   z SC26 122 7a 172 
  ESC ^[     27 1b 33   ; L27 59 3b 73   [ T27 91 5b 133   { SC27 123 7b 173 
  FS  ^\     28 1c 34   < L28 60 3c 74   \ T28 92 5c 134     SC28 124 7c 174 
  GS  ^]     29 1d 35   = L29 61 3d 75   ] T29 93 5d 135   } SC29 125 7d 175 
  RS   ^^    30 1e 36   > L30 62 3e 76   ^ T30 94 5e 136   ~ SC30 126 7e 176 
  US   ^_    31 1f 37   ? UNL 63 3f 77   _ UNT 95 5f 137 DEL SC31 127 7f 177 
  __________________________________________________________________________ 

  GTL   Go To Local.               PPU        Parallel Poll Unconfigure.      
  SDC   Selected Device Clear.     SPE        Serial Poll Enable.             
  PPC   Parallel Poll Configure.   SPD        Serial Poll Disable.            
  GET   Group Execute Trigger.     L0-L30     Listen addresses (32+ADDR).     
  TCT   Take Control.              UNL        Unlisten (= L31).               
  GTL   Go To Local.               T0-T30     Talk addresses (64+ADDR).       
  LLO   Local Lockout.             UNT        Untalk (= T31).                 
  DCL   Device Clear.              SC0-SC31   Secondary commands (96+ADDR).   
  __________________________________________________________________________ 
 

[3.0] HPIB Tutor (3): IEEE 488.2 -- Overview & Data Formats

* This chapter and the next discusses the IEEE 488.2 specification.



BACK TO INDEX

[3.1] OVERVIEW

* The 488.1 spec addressed the fundamental problems of interconnecting digital devices, defining the mechanical and electrical requirements and the basic communications protocols.

Clearly that wasn't enough. Even though HPIB devices could be connected in a mechanical, electrical, and logical fashion, that didn't guarantee that they could communicate. Devices from different vendors had wildly differing HPIB capability sets, and used incompatible data formats, serial-poll status formats, and entirely different command formats.

IEEE 488.2-1987 was defined to address these problems. 488.2 provides:

This chapter discusses the details of data formats and protocols. The following chapter discusses the common command set and status reporting.

* The minimum required set of interface capabilities defined by 488.2 is given below:

This minimum capability set states that all HPIB devices must be able to send and receive data, request service, and respond to a device clear command. It also details the minimum capabilities that a device must have when it implements controller, parallel poll, and remote-local functions.

* 488.2 defines a set of data formats. For example, it defines a format for binary, octal, and hexadecimal numbers, as well as formats to send long blocks of 8-bit bytes or strings of ASCII characters. The table below lists the supported formats:

488.2 introduced a new concept that makes it possible for older devices to communicate with devices that use this new standard: "forgiving listening -- precise talking."

Forgiving listening means that a 488.2 device can accept a wide range of data formats. Precise talking means that a 488.2 device will transmit data in a rigorous set of formats.

* Device message protocols allow devices to communicate by defining how to send device commands, parameters, and data. 488.2 "syntax" defines what to do when a device receives multiple commands, an incomplete command, or is interrupted while processing a command.

488.2 also defines the protocols by which devices exchange data. For example, it describes the order in which data is sent; requires that a device cannot send data until commanded to do so; and specifies that when a device receives a new command it will flush its output queue, and respond to that command.

[3.2] DATA CODING & FORMATS

* 488.2 specifies three sets of codes for operation with HPIB devices:

Using these codes, 488.2 defines data formats for decimal, octal, and hexadecimal integers, decimal floating point numbers, strings, character strings, and arbitrary strings. Most of these formats use ASCII characters to represent the data.

In sending ASCII and 8-bit binary, the order of the bits in the byte sent over the HPIB matches the numbering of the DIO lines. That is, bit 1 of an ASCII character matches DIO line 1. When sending streams of bytes, the most-significant byte in the stream is sent first.

The data formats are concisely described in 488.2 using "railroad track" diagrams, which provide a flowchart of the approved order of the elements of the data format. The detail provided by these diagrams is not necessary for this discussion, so we will base our descriptions on a simple description and some examples.

The device listening formats are described below. They are known as "program formats" since they are used to configure the instrument, though the formats do not necessarily define device programming commands as such.

* The <Decimal Numeric Program Data> format is also known as <NRf> for "flexible Numeric Representation". This is basically an ASCII decimal numeric string floating-point format. Legal numbers in this scheme include:


      .123        
     0.123
   123.        
    12.3
   +12.3
   -12.3       
   +12.3e10    
   -12.3E10
    12.3E+10    
    12.3E-10    
    12.3 E-10   
    12.3 e - 10
 

The mantissa cannot have more than 255 characters, and the exponent must be in the range of -32,000 to 32,000.

If a device receives an <NRf> of greater precision than it can handle, it rounds off the number. Rounding ignores the sign of the number; values less than 1/2 round down, and values greater than or equal to 1/2 round up. For example, suppose we have an instrument that can only handle two digits; rounding is performed as follows:


    1.3499 -->  1.3    
    1.35   -->  1.4      
   -2.456  --> -2.5   
   -2.447  --> -2.4
 

A suffix, used to define the units and (optionally) the multipliers of the data, may also be used with <NRf> data. The defined unit suffixes are as follows:


   _________________________________________________________________________

   Class                Preferred Suffix           Allowed Suffix
   _________________________________________________________________________

   Ratio                DB     Decibel                   
                        PCT    Percent                   
                                                   PPM    Parts Per Million

   Angle                RAD    Radian                    
                        SR     Steradian                 
                                                   DEG    Degree
                                                   GON    Grade
                                                   MNT    Minute of arc
                                                   SEC    Second
                                                   REV    Revolution

   Time                 S      Second                    
                                                   D      Day
                                                   HR     Hour
                                                   MIN    Minute
                                                   ANN    Year

   Frequency            HZ     Hertz                     
                                                   MHZ    Megahertz

   Temperature          CEL    Degree Celsius            
                        K      Degree Kelvin             
                                                   FAR    Degree Fahrenheit

   Length               M      Meter                     
                                                   FT     Feet
                                                   IN     Inch
                                                   MI     Mile
                                                   NAMI   Nautical Mile
                                                   ASU    Astronomical Unit
                                                   PRS    Parsec

   Volume               L      Liter                     
   Mass                                            G      Gram
                                                   TNE    Tonne

   Atomic Mass          U      Atomic Mass Unit          
   Energy               J      Joule                     
                                                   EV     Electronvolt

   Power                W      Watt                      
                        DBM    DB On 1 Milliwatt         

   Force                N      Newton                    
   Pressure             ATM    Atmosphere                
                        INHG   Inches of Mercury         
                        PAL    Pascal                    
                        TORR   Torr                      

   Fluid Pressure       BAR    Bar                       
   Chemical Measure     MOL    Mole                      
   Viscosity            ST     Stokes                    
                        P      Poise                     

   Charge               C      Coulomb                   
   Current              A      Ampere                    
   Potential            V      Volt                      
   Resistance           OHM    Ohm                       
                                                   MOHM   Megohm

   Conductance          SIE    Siemens                   
   Capacitance          F      Farad                     
   Inductance           H      Henry                     
   Luminous Intensity   CD     Candela                   
   Illuminance          LX     Lux                       
   Luminous Flux        LM     Lumen                     
   Magnetic Induction   T      Tesla                     
   Magnetic Flux        WB     Weber                     
   Radioactivity        BQ     Becquerel                 
   Absorbed Dose        GY     Gray                      
   Dose Equivalent      SV     Sievert                   
   _________________________________________________________________________
 

The defined multipliers are as follows:


   ___________________________

   exponent   mnemonic   name
   ___________________________

   1E18       EX         EXA
   1E15       PE         PETA
   1E12       T          TERA
   1E9        G          GIGA
   1E6        MA         MEGA
   1E3        K          KILO
   1E-3       M          MILLI
   1E-6       U          MICRO
   1E-9       N          NANO
   1E-12      P          PICO
   1E-15      F          FEMTO
   1E-18      A          ATTO
   ___________________________
 

In the latest incarnation of 488.2, <Suffix Program Data> may also be used on its own, without use of a preceding <NRf> element.

* The <Non-Decimal Numeric Program Data> format is a numeric string representation of hexadecimal, octal, and binary numbers:


   #HA2F      a hexadecimal A2F
   #ha3e      a hexadecimal a3e
   #hA3f      a hexadecimal A3f
   #Q73       an octal 73
   #q54       an octal 54
   #B01101    a binary 01101
   #b10010    a binary 10010
 

* The <String Program Data> format is for sending ASCII strings (using 7-bit USASCII characters):


   'this is a legal string'
   "this is also a legal string"
   "this string contains an embedded ' that is not a delimiter"
   'this string contains an embedded " that is not a delimiter'
   "this string contains an embedded "" that is not a delimiter"
 

Note that the two last examples do exactly the same thing, but in different ways.

* The <Arbitrary Block Program Data> spec provides a scheme for sending binary or 8-bit ASCII) data. There are two formats: a definite-length format and an indefinite-length format.

Both formats start with a "#" character to distinguish them from other device-listening formats. In the definite-length format, the "#" character is followed by:

This format may be a little easier to understand with some examples (note that <DAB> stands for some arbitrary data byte):


    #15<DAB><DAB><DAB><DAB><DAB>
    #213<DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB>
 

In the first example, the length field is 1 digit long and specifies 5 following data bytes. In the second example, the length field is 2 digits long and specifies 13 following data bytes.

In the indefinite-length format, the length field evaluates to 0 and is followed by a stream of data bytes that is terminated by a newline (line-feed) character, along with assertion of the EOI line. (It is necessary to use EOI because arbitrary data bytes will often evaluate to a line-feed character, a revelation that novice I/O programmers usually find out about the hard way.) For example:


   #0<DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB>NL&EOI
 

* The <Expression Program Data> format evaluates to a scalar, vector, matrix, or string value. It is very general-purpose and consists solely of a string of ASCII characters in the range of codes 32 to 126, with the exception of 5 characters: very


   [ " ]     [ # ]     [ ' ]     [ , ]     [ ; ]
 

-- with the entire string enclosed in parentheses. This format basically evaluates to ANY sequence of characters enclosed in parenthesis. It can be considered an "escape" format that allows for command formats not allowed by the rest of the 488.1 spec.

The device listening formats discussed above are very broad and forgiving. The device talking formats are much more precise.

* The <NR1 Numeric Response Data -- Integers> format defines integer decimal numbers with no decimal point or fractional part. For example:


      123
     +123
   -12345
 

* The <NR2 Numeric Response Data -- Fixed Point> format defines decimal numbers with a fractional part but no exponent. For example:


   12.3
   +1.234
   -0.12345
 

* The <NR3 Numeric Response Data -- Floating Point> format defines decimal numbers with a fractional part and an exponent. For example:


        1.23E+5
      123.4E-56
   -12345.678E+90
 

* The <Hexadecimal Numeric Response Data> format is exactly the same as the listening format for hex numbers, except that lowercase letters are not allowed. For example:


   #HAD0E
   #H01F2
   #HF3B
 

* The <Octal Numeric Response Data> format is exactly the same as the listening format for octal numbers, except that lowercase letters are not allowed. For example:


   #Q7035
   #Q30572
   #Q765432
 

* The <Binary Numeric Response Data> format is exactly the same as the listening format for binary numbers, except that lowercase letters are not allowed. For example:


   #B01101
   #B10101010
   #B1011
 

* The <Character Response Data> format defines the means by which mnemonic strings are sent between devices. These strings contain only ASCII numeric digits, upper-case ASCII alphabetic characters, and the "_" character. They must start with an upper-case ASCII alphabetic character, and cannot be more than 12 characters long. For example:


   START
   R2_D2
 

* The <String Response Data> format defines how a device sends an arbitrary text string. It is the same as the listening format, except that double-quotes are legal characters but single-quotes are not. For example:


   "You say hello"
   "I say ""Goodbye""."
 

* The <Definite Length Arbitrary Block Response Data> format is for sending binary data of a specified length. It is exactly the same as the listening format:


   #3128<DAB1><DAB2><DAB3> ... <DAB128>
 

* The <Indefinite Length Arbitrary Block Response Data> format is for sending binary data of an unspecified length. It is exactly the same as the listening format:


   #0<DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB><DAB>NL&EOI
 

* The <Arbitrary ASCII Response Data> format allows a device to respond with undelimited ASCII text. It consists of a stream of ASCII bytes terminated by a newline-with-EOI. This is a very general (and somewhat ill-defined) format -- note that it allows for responses that could easily be confused for other response types -- and its use is discouraged. very

* The <Expression Response Data> format is the response counterpart to the <Expression Program Data> type. It is also general-purpose and consists solely of a string of ASCII characters in the range of codes 32 to 126, with the exception of 5 characters:


   [ " ]     [ # ]     [ ' ]     [ , ]     [ ; ]
 

-- with the entire string enclosed in parentheses. Like the response data format, this format is used to cover any format not otherwise covered in the 488.2 spec.

[3.3] SYNTAX

* In the previous section we discussed the data formats defined by 488.2 -- the "words" of the "language", so to speak. In this section we move up from simple "words" to the syntax that provides a framework for those "words".

As with the data formats, the syntax that a device will recognize is much less precise than the syntax that it will generate -- "forgiving listening, precise talking" again.

* The elements of listening syntax fall into the following categories:

There is only one form of terminator. The <Program Message Terminator> defines how to terminate a message to a listening device. There are three possible terminators:

A terminator is also sometimes informally referred to as an "arnold", but this usage is clearly outside of the 488.2 spec.

* Separators fall into three categories. The <Program Message Separator> is just a ";" (semicolon), and is placed between commands in a single message to create a complex command.

The <Program Header Separator> is just blank ("white") space, and is used to separate commands and their parameters. This is the only case where white space is significant in 488.2. In other listening formats it is ignored, and in talking formats is not usually generated.

The <Program Data Separator> is just a "," (comma), and is used to separate data in a data stream.

* Commands, or more properly <Command Program Headers>, also fall into three categories, though in this case the categories are less distinct.

The <Simple Program Header> is just a command string, or <Program Mnemonic>. Legal command strings consist of lowercase and uppercase letters, plus the "_" (underscore) character. For example:


   MEASURE
 

The <Compound Command Program Header> is a set of <Program Mnemonic> strings, separated by ":" (colon) characters. A ":" may be added in front as well. For example:


   MEASURE:VOLTAGE
   :MEASURE:VOLTAGE
 

The <Common Command Program Header> is the format for the common commands defined by 488.2. Their distinguishing feature is that they are preceded by a "*" (asterisk). For example:


   *IDN
   *RST
   *SRE
 

* There are three queries, or more properly <Query Program Headers>. The queries are used to interrogate a device for information. The three queries are complementary to the three commands, and include:

The three have the same syntax as the complementary commands, except that a "?" is tacked on to the end.

* The talking syntax is similar to the listening syntax, but much more concise. The talking syntax applies to two types of data that a device may return in response to a query:

There are only four elements to the talking syntax:


[4.0] HPIB Tutor (4): 488.2 Common Commands & Status

* The 488.2 spec also includes a "common command" set that provides a minimal subset of instrument commands, as well as a consistent way of returning status information. This chapter describes these issues in detail.



BACK TO INDEX

[4.1] 488.2 COMMON COMMANDS & STATUS OVERVIEW

* The common commands defined under 488.2 are not bus commands, but strings sent as data with ATN off. (These common commands include both commands and queries, but for convenience they are collectively referred to as commands.) The complete common command set is as follows:

The spec defines some of these commands as required, and some as optional. In practice the required commands are always implemented on any respectable modern instrument, while most of the optional commands are implemented only on certain classes of instruments or never at all.

* 488.2 provides a major enhancement of the definition of the serial poll status byte defined in 488.1 spec. The original definition only defined bit 6 as the "request service" flag; 488.2 also defines two more bits, the Event Status Bit (ESB) and Message Available (MAV), plus an additional status register and provisions for others. (488.2 also includes an expansion of the definition of parallel poll provided in 488.1.)

* The 488.2 common command set makes programming a device somewhat simpler as it predefines certain elementary commands common to many devices. However, it does not address the command syntax relevant to the specific functions of the devices. That domain is covered by the SCPI standard, the subject of the following chapter.

[4.2] ESSENTIAL COMMON COMMANDS

* In practice, the most important common commands are those outlined below:

* The *IDN? (Identification) query causes a device to return a string to identify itself; this string has the format:


   <manufacturer>,<model>,<serial_number>,<firmware_rev_level>
 

Note that the serial number and firmware revision level are returned as "0" if not available. For example, a device might return a string of the form:


   HEWLETT-PACKARD,347A,222101113,A1
 

* While the *LRN? (Learn Device Setup) query is optional, many devices implement it; it tells the device to return a "learn string" to the controller that contains the commands necessary to put the device back into its current state. This string can either be in ASCII or binary format, since the format isn't specified by 488.2. Oddly, there is no *LRN command, just a *LRN? query.

* The *RST (Reset) command resets the device. It performs the following actions:

The *RST command does not affect:

Note that *RST is the highest of three levels of resets defined under 488.1 and 488.2. These three levels are:

* The *TST? (Self-Test) query causes the device to perform an internal selftest and report back the status of the test. It is similar to the *CAL? command and, like the *CAL? command, returns "0" if successful, and an error code in the range "-32767" to "32767" if not.

* The *OPC (Operation Complete) command tells the device to set bit 0 in the Standard Event Status Register (described in the next section) when it completes all pending operations.

The matching *OPC? query tells the device to place an ASCII "1" in the device's output queue when it completes all pending operations.

* The *WAI (Wait to Continue) command makes the device wait until all previous commands or queries complete, rather than execute a new command in an overlapped fashion. The device then continues executing commands that follow the *WAI command.

* The *CLS (Clear Status) command clears the status register and associated status data structures summarized in the Status Byte, such as the Event Status Register (described in the next section).

* The *ESE (Standard Event Status Enable) command allows you to set the contents of the Standard Event Status Enable Register. It takes a decimal numeric string in the range "0" to "255", representing the bit pattern in the register. If a bit is set, the corresponding bit in the Standard Event Status Register will be flagged into the Status Byte.

The *ESE? query interrogates the Standard Event Status Enable Register. It returns a decimal numeric string in the range "0" to "255".

The *ESR? (Event Status Register) query reads the contents of the Standard Event Status Register; the SESR is then cleared. A decimal numeric string in the range "0" to "255", representing the bit pattern in the SESR, is returned. This is explained in more detail in the next section.

* The *PSC (Power-On Status Clear) command (which is optional, but often implemented) controls the clearing of the Service Request Enable Register, the Standard Event Status Enable Register, the Parallel Poll Enable Register, and (in the latest flavor of 488.2) such device-specific registers as the implementor may find useful to reset.

Sending a "0" with the "*PSC" command sets the power-on clear flag, causing the three registers to be cleared at power-up. Sending any other number in the range "-32767" to "32767" clears the power-on clear flag, but leaves the registers in their previous state.

The *PSC? query returns the status of the power-on clear flag. It returns "1" if the flag is set, and "0" if the flag is cleared.

* The *SRE (Service Request Enable) command sets the Service Request Enable Register (discussed in next section). It takes a decimal numeric string in the range "0" to "255" as a parameter, with the string representing the bit pattern to be stored in the register. Any bit enabled will cause an SRQ when the matching bit in the status byte is activated.

The *SRE? query returns the contents of the Service Request Enable Register. The contents are returned as a decimal numeric string in the range "0" to "63", "128" to "191". (The gap in the range is due to the fact that bit 6, the RQS bit, cannot be set and is always returned as "0".)

The *STB? (Status Byte) query reads the device Status Byte, with bit 6 representing the Master Summary Status (MSS) bit instead of the RQS bit. The query returns a decimal numeric string in the range "0" to "255". This is explained in more detail in the next section.

* The *TRG (Trigger) command performs the same function as the GET command byte.

[4.3] STATUS REPORTING

* The 488.1 spec, as described in previous chapters, defined a status byte to be returned by a device in response to a serial poll. However, the only thing that 488.1 defined in this byte was bit 6, which was set if the polled device had asserted a service request.

488.2 expands on this status reporting scheme and allows the status to be retrieved not only via through a serial poll, but also through the 488.2 *STB? query. 488.2 also extends the definition of the status byte and provides an additional, second-level status register, plus a mechanism for determining whether or not a status flag can cause an SRQ. The following illustration diagrams the 488.2 status model (explanations follow):


                                             Status Byte
                                         +-----+   +-----+   
                                         | 0   +-->| 0   +-->-+
                                         |     |   |     |    |
                                         | 1   +-->| 1   +-->-+
                                         |     |   |     |    |
                                         | 2   +-->| 2   +-->-+
                                         |     |   |     |    |
                                         | 3   +-->| 3   +-->-+
                                         |     |   |     |    +-[OR]-+
                  from output queue ---->| MAV +-->| MAV +-->-+      |
                                         |     |   |     |    |      |
  +-----+   +-----+           +--------->| ESB +-->| ESB +-->-+      |
  | OPC |   | OPC +-->-+      |          |     |   |     |    |      |
  |     |   |     |    |      |    +---->| RQS +-->| --- +-->-+      |
  | RQC |   | RQC +-->-+      |    |     |     |   |     |    |      |
  |     |   |     |    |      |    |     | 7   +-->| 7   +-->-+      |
  | QYE |   | QYE +-->-+      |    |     +-----+   +-----+           |
  |     |   |     |    |      |    |      *STB      *SRE <mask>      |
  | DDE +-->| DDE +-->-+      |    |                *SRE?            |
  |     |   |     |    +-[OR]-+    +---------------------------------+
  | EXE +-->| EXE +-->-+
  |     |   |     |    |
  | CME +-->| CME +-->-+
  |     |   |     |    |
  | URQ +-->| URQ +-->-+
  |     |   |     |    |
  | PON +-->| PON +-->-+
  +-----+   +-----+
   *ESR?     *ESE <mask>
             *ESE?
 

In 488.2 bits 4, 5, and 6 in the status byte are defined as follows:

The other bits, as before, are undefined. However, the other bits are intended to be used as status-summary bits for device-dependent event registers. (The SCPI spec defines these bits in more detail.)

The second status register defined by 488.2, the Standard Event Status register (SRER), contains the following flags:

As noted earlier, the ESB bit in the status bit register is set if any standard events occur -- that is, if any enabled bit in the SESR is set.

The SESR can be read with the *ESR? query. The corresponding standard event status enable register can be set (to enable events on the SESR bits) with the *ESE <mask> command, and read with the *ESE? query.

The SESR is cleared by a *CLS command, reading the SESR with *ESR?, or by a power cycle (though in this last case the PON bit will be set after the SESR is cleared).

The 488.2 spec allows other event registers to be implemented and summed into the unused bits of the status byte, but does not define what these other registers to be. (The SCPI spec added these definitions with a vengeance!)

* The device data output queue has been mentioned several times in this discussion; it stores output messages to be read from the device, and can be read simply by addressing the device to talk and then handshaking the bytes. The MAV bit will be set as long as there are bytes available.

The *CLS command does not clear the output queue. It can only be cleared by the *RST command, the 488.1 DCL (device clear) command byte, or by power-cycling. This reduces the chances of losing data.

* 488.2 enhances the parallel poll protocol defined in 488.1 by adding a Parallel Poll Enable Register. Again, as Parallel Poll is rarely used, this will not be discussed further.

* The following example program -- which is for a 34401 DMM, but will work on any 488.2-compatible instrument -- uses the common commands to conduct a device verification. Note how the results of the self-test are obtained by programming the DMM to assert SRQ when done.


   10    DIM S$[50]                    ! Dimension a string.
   20    CLEAR SCREEN                  ! Clear display.
   30    ASSIGN @Dmm TO 722            ! Assign path to DMM.
   40    !
   50    ON TIMEOUT 7,5 GOTO Timetrap  ! Jump on 5-second timeout.
   60    !
   70    DISP "Clearing DMM!"
   80    CLEAR @Dmm                    ! Send SDC to DMM.
   90    OUTPUT @Dmm;"*RST;*CLS"       ! Reset & clear status.
   100   !
   110   DISP "Getting DMM status!"
   120   OUTPUT @Dmm;"*IDN?"           ! Get ID from DMM.
   130   ENTER @Dmm;S$
   140   DISP S$
   150   !
   160   WAIT 2                        ! Delay 2 seconds.
   170   DISP "Testing DMM!"
   180   ON INTR 7 GOTO Srqtrap        ! Set up interface event.
   181   ENABLE INTR 7;2               ! Enable trap on SRQ.
   190   OUTPUT @Dmm;"*ESE 1;*SRE 32"  ! Enable SRQ on OPC.
   191   OUTPUT @Dmm;"*OPC?"           ! Clear any current pending OPC.
   192   ENTER @Dmm;S$
   200   OUTPUT @Dmm;"*TST?;*OPC"      ! Test DMM, flag OPC.
   210   LOOP                          ! Wait for SRQ.
   220   END LOOP
   230   !
   240 Timetrap:                       ! Go here on timeout.
   250   DISP "Timed out -- done!"
   260   STOP
   270   !
   280 Srqtrap:                        ! Go here on SRQ.
   281   DISP "Got SRQ!"
   290   ENTER @Dmm;S$
   300   DISP "Test result: ";S$;" - done!"
   310   END
 

Note how the device is cleared with a CLEAR command and by sending the *RST;*CLS string. This is the recommended means of clearing a 488.2 device back to a known state.

Note also how this program sets up a "timeout" on the HPIB interface which causes a jump if an HPIB action takes longer than the specified timeout. For the sake of keeping things simple, most of the examples in this document don't set a timeout, but you should always do this in your own programs, since your program will hang indefinitely if you don't.

As a self-test takes a long time, it is likely to exceed a specified timeout, so this program configures the DMM to do an SRQ when the test operation is complete. It would actually be just as simple in this case to use SPOLL to query the Status Byte and check for Bit 6 set, but knowing how to set up an SRQ is useful in general.

[4.4] SECONDARY COMMON COMMANDS

* The remaining commands are implemented only in certain classes of instruments, or aren't implemented at all.

* The optional Macro Commands allow a device to accept "macro" strings that designate and instruct the device to execute a specific series of commands.

The *DMC (Define Macro) command sets up a relationship between a macro name and the commands the macro will execute. The macro is defined by sending the *DMC command, followed by a arbitrary block program element or string designating the label, followed by a string defining the macro; for example:


   *DMC "HOME",#18MOVE 0,0
 

-- defines a command that moves a pen plotter to its home position.

Macro definitions also allow the user to pass parameters within the macro; dummy parameters appear as a "$", followed by a single digit in the range "1" to "9", within the macro definition. The dummy parameter can be used several times within the macro definition string.

The macro label may be either in the form of a command or query, though it cannot be the same as a common command or query. It may be the same as a device-dependent command; when the macro label is the same as a device-dependent command, the device will execute the macro instead of the device command (as long as macros are enabled).

The *EMC (Enable Macro) command enables and disables operation of macros; if it is sent with a parameter of "0" it disables macros, if it is sent with a parameter in the range "-32767" to "32767" will enable macros. Note that this command only disables macro operation. The macros will retain their definitions and will regain their functions when enabled again. The matching *EMC? (Enable Macro) query returns "1" if macros are enabled and "0" if they are disabled.

The *GMC? (Get Macro Contents) query allows the user to inspect the definition of a particular macro; the user send "*GMC?" followed by the macro label, and the device sends back the macro definition. For example, sending:


   *GMC? "HOME"
 

-- returns the definition for "HOME", which is "#18MOVE 0,0", as shown in an earlier example.

The *LMC? (Learn Macro) query returns the labels of all currently-defined macros, as strings separated by commas. If no macros are defined the device will return a null string (""). The response will be the same whether macros are enabled or disabled.

The *PMC (Purge Macro) command wipes all defined macros from device memory.

The *RMC (Remove Individual Macro) command (added in the latest version of 488.2) allows the user to get rid of a single macro. The name of the macro to be deleted is included as a string parameter to the command.

* The auto-address commands -- *AAD and *DLF -- allow a controller to software-configure an HPIB system. Since this capability is optional, however, there is no necessity that all the devices in an HPIB system implement auto-addressing even if they are 488.2-compliant, and so this capability is in practice useless.

* The *OPT? (Option Identification) query tells the device to return its options as a string containing fields separated by commas. Note that missing options are returned as a "0", and that if the device has no options, it also returns a "0". The maximum length of the response is 255 characters.

* The *PUD (Protected User Data) command stores up to 63 bytes of device-dependent data. The data can be retrieved with a *PUD? query.

* The *RDT (Resource Description Transfer) command is similar to *PUD, but it writes a data that provides information describing the device. A matching *RDT? query retrieves the stored data.

* The *CAL? (Calibration) query tells the device to perform a self-calibration. It returns "0" if successful, or an error code from "-32767" to "32767" if not.

* The parallel poll commands -- *IST?, *PRE, and *PRE? -- support Parallel Poll operations, which almost nobody uses to begin with. They will not be discussed further.

* The *DDT (Define Device Trigger) command stores a sequence of commands that a device will execute when it receives a GET command byte or a *TRG common command. It has a matching *DDT? query.

* The *PCB (Pass Control Back) command is used by the active controller to tell what device to return control to after control has been passed to it. The command takes a decimal numeric string in the range of "0" to "30", representing the controller's address, as a parameter.

* The instrument state commands allow a device to store a configuration in its own memory and then recall it later. The *RCL (Recall Instrument State) command restores the device state from a state definition stored in local (device) memory. The command takes a number defining which memory block to use, with the numbers starting at "0" and going up to a device-defined upper limit. The state restored by the *RCL command are the same functions affected by the *RST command. (The device may have a protection mechanism that prevents the recall unless it is enabled.)

The *SAV (Save Instrument State) command stores the device state in local memory. The command is followed by a numeric parameter defining which block to use. (The device may have a protection mechanism that prevents the store unless it is enabled.)

The *SDS (Save Default Device Settings) command allows a default state definition to be stored in a given memory block in the device. The command takes a number (as defined for *RCL and *SAV) defining which memory to restore to its default setting.


[5.0] HPIB Tutor (5): Introduction To SCPI

* This chapter provides an overview of the Standards Commands for Programmable Instruments (SCPI) command set spec.



BACK TO INDEX

[5.1] SCPI OVERVIEW

* The SCPI specification defines a programming language used to control test and measurement instruments such as oscilloscopes, function generators, power supplies, and spectrum analyzers. Such instruments implement SCPI in their firmware.

SCPI is in some senses a follow-on to IEEE 488.2. The 488.2 spec defined general commands, while SCPI provides the commands required for the operation of specific types of instruments.

The first pass at a more comprehensive programming language spec was HP's Test & Measurement Language (TMSL), announced in August 1989 and offered as an industry standard. This first attempt defined 850 commands. In April 1990, a consortium of manufacturers adopted the TMSL definition as the basis for SCPI, incorporating some features (a Data Interchange Format, or DIF) proposed by Tektronix.

The initial SCPI consortium consisted of HP, Tektronix, Fluke, Phillips, Wavetek, Racal-Dana, Keithley, Bruel & Kjaer, and National Instruments. The SCPI Consortium now maintains the SCPI definition and the formal document that describes it.

The benefit of SCPI is compatibility -- that is, interoperability between different instruments. The same command that performs a certain function on one instrument will perform exactly that same function on an entirely different instrument, as long as both share that capability. An instrument control program designed for a certain type of instrument, such as a function generator, will work for a comparable function generator from a different vendor with few or no changes.

SCPI is designed with commands at several levels of generality to help provide this compatibility. A high-level SCPI command such as MEASURE:VOLTAGE:AC? ("read an AC voltage") will work on both an oscilloscope and a DVM. At the same time, SCPI also provides commands for low-level instrument control that allow precise instrument programming, but are not likely to work on another instrument.

While SCPI may seen a little intimidating and obscure at first (some refer to it as "C for instruments"), it is much more consistent and understandable than other instrument command sets. Since it does cover the full range of programmable instrumentation, the full SCPI spec is of course complicated, but the basic rules are not hard to understand and you can pick them up easily.

[5.2] SCPI COMMAND SYNTAX

* SCPI is, as noted, a superset of the 488.2 spec in terms of its data formats, its usage of common commands, and the 488.2 status system, and uses much of the same nomenclature. SCPI "program messages", for example, are the data sent from the controller to the instrument. Similarly, SCPI "response messages" are the formatted data returned from the instrument to the controller. They both adhere to the 488.2 principle of "forgiving listening, precise talking".

Also as with 488.2, SCPI defines both commands and queries. One of the nicer principles on which SCPI is based, in fact, is if there is a command that sets a value, there is a matching query that reads back that value.

The 488.2 commands encompassed by SCPI were explained in the previous chapter and will not be examined in any more detail here. The "subsystem commands" are the heart of SCPI and the focus of the rest of this discussion.

* SCPI organizes commands into various sets that match "subsystems" of the target instrument. The commands for each subsystem are defined in a hierarchical structure similar to the hierarchical file system found on most computers. In SCPI, this command structure is called a "command tree". A simplified example, for the SENSe command as implemented on a DMM, is shown below:


                              SENSe
                                |
                +---------------+---------------+
                |                               |
             CURRent                         VOLTage
                |                               |
         +------+------+                 +------+------+
         |             |                 |             |
       RANGe       RESolution          RANGe        RESolution
         |             |                 |             |
     +---+---+         |             +---+---+         |
     |       |         |             |       |         |
   UPPer    AUTO      AUTO         UPPer    AUTO      AUTO
 

Definitions of the other subsystems are irrelevant for the moment. The SENSe subsystem is just a good way to discuss the syntax of SCPI, and other subsystems will be illustrated in the next section.

The command tree is described with nomenclature similar to that used for file systems. The command at the top of the tree is the "root" command, and subsystem commands are linked into "paths" through the tree. For example, one path through the tree is defined by the command sequence:


   :SENSe:VOLTage:RANGe:AUTO
 

-- which sets the DMM to read voltages and uses autoranging. Note how colons (":") are used as path separators. Another path is:


   :SENSe:CURRent:RANGe:UPPer
 

-- which sets the DMM to read currents and uses the upper current range of the DMM. Note that the full path of a command does not need to be sent to the DMM each time, but how and why that is so needs more detailed explanation. not

Commands sent to an instrument are intrepreted by a software routine called a "parser". When decoding SCPI subsystem commands, the parser has to keep track of the "current path" of the command, which is something like the "current directory" in a hierarchical file system: it specifies the subsystem block the DMM is decoding commands for.

The parser navigates through the tree as directed by subsystem command strings according to the following rules:

For example:


   :SENSe:VOLTage ; RANGe:AUTO ; RESolution:AUTO
 

-- is the same as executing:


   :SENSe:VOLTage:RANGe:AUTO
   :SENSe:VOLTage:RESolution:AUTO
 

Note that the spaces around the ";" are strictly window-dressing. The parser ignores them, they're just there to make the string easier to read. Similarly:


   :SENSe:VOLTage:RANGe:AUTO ; :SENSe:CURRent:RANGe:UPPer
 

-- is the same as executing both commands separately, since the ":" immediately following the separating ";" resets the current path to root.

* The command tree is specified concisely through a "subsystem command table" that define the commands and their parameters. For example, the SENSE command tree illustrated previously evaluates to the following command table:


   _______________________________________

   Command                 Parameters
   _______________________________________

   [:SENSe]               

      :CURRent            
         :RANGe           
            :AUTO          Boolean or ONCE
           [:UPPer]        numeric
         :RESolution       numeric
            :AUTO          Boolean or ONCE

      :VOLTage            
         :RANGe           
            :AUTO          Boolean or ONCE
           [:UPPer]        numeric
         :RESolution       numeric
            :AUTO          Boolean or ONCE
   _______________________________________
 

The hierarchy of the command paths is given by the level of indenting in the "Command" column of the table. Following the indenting yields subsystem command strings of the form:


   :SENSe:CURRent:RANGe:AUTO ON
 

As you should have noticed by now, most of the keywords are listed as strings of uppercase letters, followed by lowercase letters. This mixing of cases is not part of the SCPI definition as such. SCPI isn't case-sensitive, and so you can send subsystem commands all upppercase, all lowercase, or any mixture of the two. not

What the lowercase letters in the definitions specify is that those characters are optional, and may be discarded if desired. To illustrate:


   :SENS:CURR:RANG:AUTO ON
 

-- is the same as:


   :SENSe:CURRent:RANGe:AUTO ON
 

The keywords in square brackets are "implied" keywords, meaning that if a subsystem command at that path level is not specified, it is assumed. For example:


   :SENSe:VOLTage:RANGe:UPPer 6.5
 

-- is the same as:


   :VOLTage:RANGe 6.5
 

An implied keyword should not be used in a command string unless it is necessary to do so. Implied keywords often are defined to define enhancements of SCPI. They are left implied to keep from "breaking" programs that use commands that conform to earlier revs. Avoiding the use of implied keywords makes it more likely a program will work with an earlier type of SCPI instrument.

For almost all commands that can set a value, there is a matching query that can read one back. This is similar to 488.2 common command queries in that the query string is the same as the comparable command string, but with a "?" tacked on. For example, the command:


   :SENSe:VOLTage:RANGe
 

-- has the matching query:


   :SENSe:VOLTage:RANGe?
 

If a table contains a keyword that ends in a "?", that means that the subsystem command string only exists as a query, and there is no command form. Other subsystem commands may not have matching queries, as they initiate events, such as device triggers, and do not set values that can be queried.

The parameters for each command, if any, are listed in the right column of the table. If any parameters are optional, they are listed in square brackets, just like the implied keywords. The ranges of optional values are defined in the documentation for a specific instrument.

Commands are sent to the instrument followed by their parameters, if any are required. Note that parameters must be separated from the command by a space, and multiple parameters are separated by commas (","). The full command sequence is terminated by a newline, an EOI, or both.

[5.3] EXAMPLE SCPI COMMAND SETS

* For examples of SCPI syntax, consider simplified command sets for a hypothetical signal generator, DVM, and relay scanner.

These devices are examples of the three classes of programmable instruments: source, sense, and switch devices:

More sophisticated instruments may combine multiple instrument functions in a single package.

Our hypothetical signal generator can produce sine, triangle, or square wave outputs. The output is programmable from 1 Hz to 100 kHz at levels of 0 to 500 mV RMS. The output impedance can be switched between 50 and 75 ohms.

At power-on, or after *RST, the signal generator is set to output a 1 millivolt RMS, 1 kHz sine wave with an output impedance of 75 ohms, although the actual output is disabled. The signal generator is programmed in fixed units of Hz, volts RMS, and ohms. The command table is illustrated below:


   __________________________________________

   Command                  Parameters 
   __________________________________________

    :OUTPut
      [:STATe]              Boolean
       :IMPedance           50 or 75

   [:SOURce]
       :FREQuency
         [:FIXed]           1 to 1e5
       :VOLTage
         [:LEVel]
            [:IMMediate]
               [AMPlitude]  0 to 0.5
       :FUNCtion
         [:SHApe]           SINe or SQUare or
                            TRIangle
   __________________________________________
 

This device incorporates two subsystems, an OUTPut subsystem and a SOURce subsystem. Note how the command set incorporates a large number of implied keywords -- a common feature of practical SCPI implementations that greatly reduces the number of commands you actually need to remember -- and simplifies to only five distinct command forms:


   :FREQ 100        Set output frequency (to 100 Hz).
   :VOLT 0.1        Set output voltage (to 100 mV RMS).
   :FUNC TRI        Set output function (to triangle wave).
   :OUTPut:IMP 50   Set output impedance (to 50 ohms).
   :OUTPut ON       Turn on outputs.
 

The matchinq queries consist of:


   :FREQ?         Query output frequency.
   :VOLT?         Query output voltage.
   :FUNC?         Query output function.
   :OUTPut:IMP?   Query output impedance.
   :OUTPut?       Query output state.
 

Note that the :OUTPut:IMP command only has two values, 50 or 75. Other values will be rounded to the allowed value.

Note also the :OUTPut ON command, which can cause problems for novices, since the output terminals of a SCPI instrument are disabled after power-on or *RST. The programmer has to use :OUTPut ON to specifically enable the outputs.

* The hypothetical DVM is capable of making either AC or DC voltage measurements. It measures input voltages from 0 to 100 volts DC or AC RMS. The DVM has two rear panel BNC ports, for the "measurement complete" output and an "external trigger" input. For better noise rejection, the DVM provides a low-pass input filter that is programmable to frequencies of 100, 200, or 1000 Hz.

After power-on or *RST, the DVM is configured to read DC voltages using autoranging and the best possible resolution. The input impedance is set to 10 megohms, and the input filter is set to 1000 Hz. The trigger source is set to IMMediate. Its command table is shown below:


   _______________________________________________

   Command                   Parameters
   _______________________________________________

    :CONFigure              
      [:SCALar]             
          :VOLTage          
             :AC             numeric,numeric (*)
            [:DC]            numeric,numeric (*)

    :FETCh                  
      [:SCALar]             
          :VOLTage          
             :AC?            numeric,numeric (*)
            [:DC]?           numeric,numeric (*)

    :INITiate               
      [:IMMediate]          

    :INPut                  
       :IMPedance            50 or 1e6
       :FILTer              
         [:LPASs]            100 or 200 or 1000

    :MEASure                
      [:SCALar]             
          :VOLTage          
             :AC             numeric,numeric (*)
            [:DC]            numeric,numeric (*)

    :READ                   
      [:SCALar]             
          :VOLTage          
             :AC?            numeric,numeric (*)
            [:DC]?           numeric,numeric (*)

   [:SENSe]                 
       :FUNCtion             AC or DC

    :TRIGger                
      [:IMMediate]          
       :SOURce               IMMediate or EXTernal
       :COUNt                numeric
   _______________________________________________

   (*):  The first numeric parameter specifies the 
   input voltage range from 0.001 to 100 volts by 
   powers of 10; the second specifies the voltage 
   resolution, which is rounded to 0.001, 0.01, 
   or 0.1 volts.  
   _______________________________________________
 

This device has 8 command subsystems that provide somewhat overlapping functionality. The commands :MEASure, :CONFigure & :READ, and :INITiate & :FETCh demonstrate how SCPI allows you to take measurements at differing levels of detail. :MEASure, for example, is very easy to use; all you need to know is what quantity you want to measure. :CONFigure & :READ are not quite as easy to use, but they are very flexible; and :INITiate & :FETCh are hard to use, but offer maximum flexibility.

The high-level commands are actually equivalent to sequences of low-level commands, so it makes sense to study the low-level commands first and then work our way up. However, in practice, a smart programmer will never use a low-level command when a higher-level one will do the job, since the higher-level commands make the job easier to implement and understand, as well as easier to port to other systems.

Most measurements can be modeled as a three-step process:

When you use low-level commands, you must do each of these steps explicitly. Typically, you begin setup by sending *RST to place the instrument into a known state, and then you change each setting, one by one, until you have the instrument configured. Then you trigger the measurement. The trigger may be generated automatically by your setup commands, or you can send an explicit trigger command. For example, an :INITiate:IMMediate command, forces the measurement to occur as soon as the command is interpreted. Finally, you can read the measurement using a :FETCh query.

For the DVM, a low-level sequence of commands to read an AC voltage looks like this:


   10 OUTPUT @Dvm;"*RST"              ! Reset into a known state.
   20 OUTPUT @Dvm;":FUNC AC"          ! Change function to AC volts.
   30 OUTPUT @Dvm;":INP:IMP 50"       ! Change input impedance to 50 ohms.
   40 OUTPUT @Dvm;":INIT:IMM"         ! Trigger a reading.
   50 OUTPUT @Dvm;":FETCH:VOLT:AC?"   ! Query for the reading.
   60 ENTER @Dvm;Vac                  ! Get the reading.
 

Let's compare this to programming the instrument with high-level commands. :MEASure is the simplest (and generally most useful) way to make and read a measurement. A single :MEASure command is equivalent to programming an instrument setting, sending an :INITiate:IMMediate, followed by a :FETCh query. The same AC volts measurement shown above can be simplified using :MEASure to:


   10 OUTPUT @Dvm;":MEAS:VOLT:AC?"    ! Measure AC volts.
   20 ENTER @Dvm;Vac                  ! Get the reading.
 

Using :MEASure does have its disadvantages. When you use :MEASure, the instrument chooses the "best" default settings to accomplish the measurement you want. Usually instrument documentation lists the settings associated with :MEASure. However, sometimes the instrument's idea of a "best" setting conflicts with your needs. For example, suppose you want to use the DVM to read an AC voltage through a 1 megohm input impedance. :MEASure won't work, because it always sets the input impedance to 50 ohms for an AC measurement.

:CONFigure and :READ offer a reasonable compromise between :MEASure and low-level commands. :CONFigure performs an instrument setup, while :READ triggers a measurement and reads back the voltage, and so :CONFigure followed by :READ is equivalent to a :MEASure. This is how you could read an AC voltage through a 1 megohm input impedance:


   10 OUTPUT @Dvm;"*RST"              ! Reset to a known state.
   20 OUTPUT @Dvm;":CONF:VOLT:AC"     ! Set up to read AC volts.
   30 OUTPUT @Dvm;":INP:IMP 1e6"      ! Set input impedance.
   40 OUTPUT @Dvm;":READ:VOLT:AC?"    ! Trigger and query for reading.
   50 ENTER @Dvm;Vac                  ! Read back the voltage.
 

* Our hypothetical scanner is a simple, 8-channel multiplexer switch. It includes two rear panel BNC ports: "channel closed" and "external trigger". At power on or after *RST, all channels are open and the trigger source is set to immediate. The command table follows:


   _______________________________________________ 

   Command                   Parameters
   _______________________________________________

   [:ROUTe]
       :CLOSe                (@0:7)
       :OPEN                 (@0:7)
       :SCAN                 (@0:7)

    :TRIGger
      [:IMMediate]
       :SOURce               IMMediate or EXTernal
   _______________________________________________
 

This is, like the source, a simple device, with only two command subsystems. Note how the Scanner uses a "channel list" as a parameter. This is a special parameter used in some :ROUTe subcommands. Typical examples of channel lists include:


   (@1)       Channel 1.
   (@1:4)     Channels 1 through 4.
   (@1,3)     Channels 1 and 3 only.
   (@1:4,7)   Channels 1 through 4, and 7.
 

The :OPEN and :CLOSe commands simply open and close switches in the channel list. The :SCAN command places a channel list into the internal memory of the switch box. Once a :SCAN has been programmed, the scanner closes channels in sequence using break-before-make as it receives each trigger, and begins again at the first channel in the list when it completes the last.

The following statements configure the scanner to scan channels 1 through 3 using the rear panel BNC external trigger:


   40 OUTPUT @Scan;"*RST;*CLS"
   50 OUTPUT @Scan;":SCAN (@1:3)"
   60 OUTPUT @Scan;":TRIG:SOUR EXT"
 

You can query the condition of any individual channel or channel list. SCPI instruments always return a 1 or a 0 in the same order that the channel list in the query was specified. The meaning of 1 or 0 depends on whether you query using the :OPEN or :CLOSe command. If you query using :OPEN, a 1 means open and a 0 means closed, while if you query using :CLOSe, a 1 means closed and a 0 means open.

The following statements perform some simple queries:


   10 OUTPUT @Scan;"OPEN? (@1)"     ! Is channel 1 open?
   20 ENTER @Scan;Ch1               ! Read back state (1=TRUE=OPEN).
   30 OUTPUT @Scan;"CLOSE? (@1)"    ! Is channel 1 closed?
   40 ENTER @Scan;Ch1               ! Read back state (1=TRUE=CLOSED).
   50 OUTPUT @Scan;"OPEN? (@1:4)"   ! Are any of channels 1 through 4 open?
   60 ENTER @Scan;Ch1,Ch2,Ch3,Ch4   ! Read back states of four channels.
 

* As an example consider programming the three instruments to test the gain of a three-stage amplifier. The signal generator drives a sine wave into the input stage of the amplifier, the scanner routes signals from the output of each stage into the DVM, and gains are computed using simple voltage ratios, not DB.

Measurement speed is optimized in this application by setting the DVM to a fixed range and performing "hardwired handshaking" between the DVM and the switch box. This is done by linking the DVM's "measurement complete" output to the switch box's "external trigger" input, and linking the switch box's "channel closed" output back to the DVM's "external trigger" input.

Each time the DVM completes a measurement, it pulses the "measurement complete" output, which is turn causes the switch box to move to the next channel in its scan list. When the switch box closes this channel, the box pulses its "channel closed" output, which feeds back to the DVM to trigger the next measurement.

The program to perform these measurements follows below:


   10   CLS
   15   INTEGER Dummy
   20   REAL Readings(0:3)
   30   !
   40   ASSIGN @Dvm TO 722                  ! Set up paths to devices.
   50   ASSIGN @Switch TO 711
   60   ASSIGN @Siggen TO 719
   70   !
   80   CLEAR @Dvm                          ! Clear device interfaces.
   90   CLEAR @Switch
   100  CLEAR @Siggen
   110  !
   120  OUTPUT @Dvm;"*CLS;*RST"             ! Reset the devices.
   130  OUTPUT @Switch;"*CLS;*RST"
   140  OUTPUT @Siggen;"*CLS;*RST"
   150  !
   160  ! Configure the DVM to measure a 500 mV RMS signal with 5 mv
   170  ! resolution.
   180  !
   190  OUTPUT @Dvm;":CONF:VOLT:AC 0.5,0.005"
   200  !
   210  ! Once armed, accept four triggers from the external trigger.
   220  !
   230  OUTPUT @Dvm;":INIT ; :TRIG:COUNT 4; SOUR EXT"
   240  !
   250  ! Set the signal generator's output frequency to 100 kHz at 500 mV
   260  ! RMS.  The output function is SINE (default at *RST).
   270  !
   280  OUTPUT @Siggen;":FREQ 1e5 ; :VOLT 0.5"
   290  !
   300  ! Change the source output frequency to 50 ohms.
   310  !
   320  OUTPUT @Switch;":SCAN (@1:4) ; :TRIG:SOUR EXT"
   330  !
   340  ! Begin measurement -- turn on the source output signal; the *OPC?
   350  ! query returns a 1 only after the output has settled.
   360  !
   370  OUTPUT @Siggen;":OUTPUT ON ; *OPC?"
   380  ENTER @Siggen;Dummy
   390  !
   400  ! Close the first channel in the switch, the hardwired triggering  
   410  ! does the rest.
   420  !
   430  OUTPUT @Switch;":INIT ; :TRIG:IMM"
   440  !
   450  ! Put readings in the output queue.
   460  !
   470  OUTPUT @Dvm;":READ:VOLT:AC?"
   480  DISP "Waiting for the measurement to complete."
   490  !
   500  ! Get readings into array as they become available.
   510  !
   520  ENTER @Dvm;Readings(*)
   530  DISP "Measurement complete."
   540  !
   550  ! Turn off signal generator output.
   560  !
   570  OUTPUT @Siggen;":OUTPUT OFF"
   580  !
   590  ! Calculate and print gains.
   595  !
   600  PRINT "Stage 1 gain = ";Readings(1)/Readings(0)
   610  PRINT "Stage 2 gain = ";Readings(2)/Readings(1)
   620  PRINT "Stage 3 gain = ";Readings(3)/Readings(2)
   630  !
   640  END
 

[5.4] SCPI DATA FORMATS

* SCPI data types are essentially derived (with some small additions) from the program data types defined in 488.2. The formats are flexible ("forgiving listening") and a quick survey should be easily understood.

Simple numeric parameters encompass familiar integer and floating-point formats:


   100
   100.
    -1.23
     4.5e3
    -7.89E-01
      .5
 

Numeric parameters are a superset of simple numeric parameters, and add certain constant values to that definition. All instruments will recognize the constants:


   MAXimum
   MINimum
 

-- though the exact value of these constants is device-dependent. Other special values, such as:


   UP
   INFinity
   DEFault
 

-- may be defined for specific instruments. For example:


   100 OUTPUT @Dvm;":VOLT:DC MAX"
   110 OUTPUT @Dvm;":CONF:VOLT:DC 10.0,Min"
 

Discrete parameters are keywords associated with a list of discrete settings in a device. Like subsystem commands, they have a long and a short form. Upper- and lower-case letters may be mixed, but the value returned for a discrete parameter by a subsystem query will always be uppercase. Samples of discrete parameters include:


   INTernal:         Specify internal trigger source.
   EXTernal:         Specify external trigger source.
   POSitive:         Specify trigger arm on positive transition.
   NEGative:         Specify trigger arm on negative transition.
   BOTH:             Specify trigger arm on either transition.
 

For some practical examples:


   100 OUTPUT @Dvm;":TRIGGER:SOURCE INT"
   110 OUTPUT @Dvm;":ARM:SLOPE NEGATIVE"
 

Boolean parameters should be familiar:


   ON
   OFF
   TRUE
   FALSE
   1
   0
 

When you query a Boolean setting, you will always get back a "1" or "0". For example:


   100 OUTPUT @Dvm;":OUTPUT ON"
   110 OUTPUT @Dvm;":OUTPUT 0"
 

String parameters allow ASCII strings to be sent as parameters. For example:


   'this is a STRING'
   "this is also a string"
   "one double quote inside brackets: [""]"
   'one single quote inside brackets: ['']'
 

Single quotes are the most convenient format for HP BASIC:


   110 OUTPUT @Dvm;":DISPLAY:TEXT 'STOP!'"
 

Block parameters are sent using the indefinite-length and definite-length block formats defined by 488.2, where the formats for indefinite-length and definite-length blocks are respectively:


   #0<DAB><DAB> ... <DAB>NL&EOI
   #<num_digits_in_byte_count><byte_count><DAB1><DAB2> ... <DABn>
 

For example, the following HP BASIC commands send the same 7 bytes of ASCII text as indefinite- and definite-length blocks respectively:


   120 OUTPUT @Dvm;"#0ABC_XYZ",END  ! END asserts EOI.
   OUTPUT @Dvm;"#17ABC_XYZ"         ! <num_digits>=1, <byte_count>=7
 

Non-decimal numeric parameters allow numeric information to be sent as binary, octal, or hexadecimal:


   #b010110100
   #Q773662
   #h3FA1
 

The header may be upper- or lower-case characters.

* As mentioned earlier, data returned to a host in response to a SCPI query is known as "response data". The response data types, which are also derived from 488.2 response data types, match the data types defined for parameters but with more concise and restricted syntax ("precise talking").

Note that multiple data elements returned in response to a query are separated by commas (","). Note also that, since multiple queries can be sent as a single program message:


   :QUERY1?;:QUERY2?
 

-- then multiple responses can also be sent as a single response message, with the responses separated by semicolons (";"). (Sending multiple queries in a single program message is bad form, though it is not illegal.) Response data is always terminated with a newline and EOI. always

Real response data defines floating-point data types with a uniform format:


      1.23E+0
     -1.0E+2
     -1.23
   -100.0
     -7.89E-01
      0.5
 

Integer response data defines an integer-only data format:


       0
    +100
    -100
     256
   65535
       4
 

Discrete response data is defined exactly as is discrete parameter data, but the response data, unlike the discrete parameter data, is always uppercase: always


   INT
   EXT
   POS
   NEG
 

String response data is defined like string parameter data, except that only double-quotes are legal:


   "this is a string"
   "one double quote inside brackets: [""]"
 

Definite-length and indefinite-length block response data types are totally identical to their parameter equivalents.

Binary, octal, and hexadecimal response data types are identical to their parameter equivalents, except that lower-case headers are not allowed:


   #B00001111
   #Q0707
   #H0F1F
 

[5.5] STATUS & TRIGGERING

* SCPI specifies advanced features for status and triggering. In fact, it defines more features than anyone could ever want.

The status system is in particular extremely complicated. As it turns out, most of the features were simply due to different HP instrument divisions promoting their own pet features when the spec was being defined, with the end result being a system that can be extremely confusing.

As a way of getting a grasp of the SCPI status system, consider a simple example: the status system of the 34401 (ALF) DMM, which is illustrated below:


         +-----+   +-----+
         | VOV +-->| VOV +-->-+
         |     |   |     |    |
         | COV +-->| COV +-->-+        VOV:  voltage overload
         |     |   |     |    |        COV:  current overload
         | 2   +-->| 2   +-->-+        OOV:  ohms overload
         |     |   |     |    |        TLO:  limit test fail lo
         | 3   +-->| 3   +-->-+        THI:  limit test fail hi
         |     |   |     |    |
         | 4   +-->| 4   +-->-+
         |     |   |     |    |
         | 5   +-->| 5   +-->-+
         |     |   |     |    |
         | 6   +-->| 6   +-->-+
         |     |   |     |    |
         | 7   +-->| 7   +-->-+
         |     |   |     |    +------------+
         | 8   +-->| 8   +-->-+            |
         |     |   |     |    |            |
         | OOV +-->| OOV +-->-+            |
         |     |   |     |    |            |
         | 10  +-->| 10  +-->-+            |
         |     |   |     |    |            |
         | TLO +-->| TLO +-->-+            |
         |     |   |     |    |            |
         | THI +-->| THI +-->-+            |
         |     |   |     |    |            |        Status Byte
         | 13  +-->| 13  +-->-+            |    +-----+   +-----+   
         |     |   |     |    |            |    | 0   +-->| 0   +-->-+
         | 14  +-->| 14  +-->-+            |    |     |   |     |    |
         |     |   |     |    |            |    | 1   +-->| 1   +-->-+
         | 15  +-->| 15  +-->-+            |    |     |   |     |    |
         +-----+   +-----+                 |    | 2   +-->| 2   +-->-+
 STAT:QUES:EVEN?   STAT:QUES:ENAB <mask>   |    |     |   |     |    |
                   STAT:QUES:ENAB?         +--->| QUE +-->| QUE +-->-+
                                                |     |   |     |    +-[OR]-+
                         from output queue ---->| MAV +-->| MAV +-->-+      |
                                                |     |   |     |    |      |
         +-----+   +-----+           +--------->| ESB +-->| ESB +-->-+      |
         | OPC +-->| OPC +-->-+      |          |     |   |     |    |      |
         |     |   |     |    |      |    +---->| RQS +-->| --- +-->-+      |
         | RQC +-->| RQC +-->-+      |    |     |     |   |     |    |      |
         |     |   |     |    |      |    |     | 7   +-->| 7   +-->-+      |
         | QYE +-->| QYE +-->-+      |    |     +-----+   +-----+           |
         |     |   |     |    |      |    |      *STB      *SRE <mask>      |
         | DDE +-->| DDE +-->-+      |    |                *SRE?            |
         |     |   |     |    +-[OR]-+    +---------------------------------+
         | EXE +-->| EXE +-->-+
         |     |   |     |    |
         | CME +-->| CME +-->-+
         |     |   |     |    |
         | URQ +-->| URQ +-->-+
         |     |   |     |    |
         | PON +-->| PON +-->-+
         +-----+   +-----+
          *ESR?     *ESE <mask>
                    *ESE?
 

This is a consistent extension of the 488.2 status system. In this case, an additional status bit, QUE (Questionable Data), is used to reflect the status of an additional status register, the Questionable Data register, which contains a subset of SCPI bit definitions required by the ALF. (Note that the bit acronyms specified are not defined by SCPI, I just made them up to make the diagram simpler.) not

The Questionable Data Register can be queried with: STAT:QUES:EVEN?. Its event enable register can be set with STAT:QUES:ENAB <mask>, and the event masks can be read with STAT:QUES:ENAB?.

While only 5 bits are defined in the Questionable Data Register on the ALF, the SCPI standard provides definitions for most of the other bits as well. Note that SCPI also defines bit 7 of the Status Byte as OPR, which reflects the status of a another 16-bit status register, the Standard Operation Status Register, that is not implemented on the ALF.

* The SCPI trigger system is also very sophisticated, but more useful. An instrument trigger system synchronizes an instrument's actions -- such as making a measurement or generating an output signal -- with specific events -- such as a software command or an external trigger input.

The SCPI triggering system can become quite complicated but a simple subset of it incoporates three levels:

This is more than enough for most purposes, and in fact many instruments don't implement even this level of triggering capabilities.

* Example commands using INIT include:


   :ABORt           Abort operations, go to idle.
   :INIT:IMM        Execute programmed operation.
   :INIT:CONT ON    Execute programmed operations continuously.
   :INIT:CONT OFF   Stop programmed operations after current one is done.
 

On their own, the INIT commands simply tell the device to do something immediately, either once, using :INIT:IMM, or continuously, using :INIT:CONT ON (with the sequence broken by :INIT:CONT OFF or ABORT).

* The TRIG commands add a layer of qualification to the triggering. The TRIG commands are very complicated, so a list of typical commands will have to do:


   :TRIG:SOURCE IMM    Trigger on INIT:IMM (default action).
   :TRIG:SOURCE INT    Trigger on internal signal (input signal).
   :TRIG:SOURCE EXT    Trigger on external trigger input.
   :TRIG:SOURCE MAN    Trigger on front-panel button or the like.
   :TRIG:SOURCE BUS    Trigger on HPIB GET or *TRG command.

   :TRIG:LEVEL 3       Specify level at which trigger occurs (5 volts).

   :TRIG:SLOPE POS     Trigger on rising edge of signal.
   :TRIG:SLOPE NEG     Trigger on falling edge of signal.
   :TRIG:SLOPE BOTH    Trigger on both edges of signal.

   :TRIG:COUPL AC      Specify AC coupling to trigger input.
   :TRIG:COUPL DC      Specify DC coupling to trigger input.
   :TRIG:DELAY 5       Specify delay of action after triggering (5 seconds).
   :TRIG:ECOUNT 4      Specify number of trigger events to cause trigger (4).
   :TRIG:HYST 0.05     Specify noise margin in trigger signal.

   :TRIG:TTL           Specify trigger on TTL signal levels.
 

This should be self-explanatory, except for the :TRIG:HYST command. It is necessary to specify a noise margin with a trigger because the input signal that causes the trigger may be noisy, and if the noise jumps around the trigger level during a signal transition, the trigger may occur multiple times when it's only supposed to happen once.

For example, suppose we trigger off an input signal hitting 3 volts on a positive slope. The hysteresis spec tells the triggering system not to trigger again until the input signal travels downward again by at least the noise margin.

To demonstrate a TRIG configuration, assume that you want to make a measurement when the input signal passes through 5 volts, with either a positive or negative slope. The signal contains noise that averages about 2 millivolts peak to peak. This could be done with the following sequence of trigger commands:


   10  OUTPUT @Dev;"*RST;*CLS"           ! Clear the device.
   20  CALL Config_dev(@Dev)             ! Set up device configuration.
   25  !
   30  OUTPUT @Dev;":TRIG:SOURCE EXT"    ! Trigger on external trigger input.
   40  OUTPUT @Dev;":TRIG:LEVEL 5"       ! Trigger at 5 V level.
   50  OUTPUT @Dev;":TRIG:SLOPE BOTH"    ! Trigger at any crossing.
   60  OUTPUT @Dev;":TRIG:HYST 0.002"    ! Compensate for noise.
   65  !
   70  OUTPUT @Dev;":INIT:IMM"           ! Wait for it.
   75  !
   80  CALL Get_trace(@Dev,Data(*))      ! Get trace from device.
 

Note how :INIT:IMM is used to tell the device to wait for a trigger. The TRIG statements merely qualify what the trigger will be. Note also the CALL statements in this listing. These invoke user-defined subprograms to perform the indicated actions.

* The ARM commands offer a second level of triggering to provide pretriggering conditions. Their syntax is effectively the same as the TRIG commands, with the keyword "ARM" substituted for "TRIG".

For example, assume that you want to measure a TTL signal input. Before triggering the measurement, you want to first capture two negative TTL edges on an input fed to the external trigger input, and then capture three negative TTL edges on the input signal itself.


   10   OUTPUT @Dev;"*RST;*CLS"         ! Clear the device.
   20   CALL Config_dev(@Dev)           ! Set up device configuration.
   25   !
   30   OUTPUT @Dev;":ARM:SOURCE EXT"   ! Arm on external trigger input.
   40   OUTPUT @Dev;":ARM:TTL"          ! Arm signal is TTL.
   50   OUTPUT @Dev;":ARM:EDGE NEG"     ! Arm on negative edges.
   60   OUTPUT @Dev;":ARM:ECOUNT 2"     ! Count two edges to arm.
   65   !
   70   OUTPUT @Dev;":TRIG:SOURCE INT"  ! Trigger on input signal.
   80   OUTPUT @Dev;":TRIG:TTL"         ! Trigger is TTL.
   90   OUTPUT @Dev;":TRIG:EDGE NEG"    ! Trigger on negative edges.
   100  OUTPUT @Dev;":TRIG:ECOUNT 3"    ! Count three edges to trigger.
   105  !
   110  OUTPUT @Dev;":INIT:IMM"         ! Wait for trigger.
   115  !
   120  CALL Get_trace(@Dev,Data(*))    ! Get trace from device.
 

The illustration below shows the operation of this trigger sequence:


          A             B
      +-------------------------------------------------------------+
      |       1         2                                           |
      |........    ......    ...................................... |
  EXT |       :    :    :    :                                      |
      |       :....:    :....:                                      |
      |                                                             |
      |     ......    ......    ......    ......    ......    ..... |
  INT |     :    :    :    :    :    :    :    :    :    :    :     |
      | ....:    :....:    :....:    :....:    :....:    :....:     |
      |                                                             |
      |                    1         2         3                    |
      +-------------------------------------------------------------+
                                               C          

    A: The :INITiate:IMMediate command begins the arming sequence.
    B: The arming conditions are satisfied (2 negative edges on D01).
    C: The trigger conditions are satisfied (3 negative edges after arm).
 

Even more complicated triggering actions could be defined as needed.


[6.0] HPIB Tutor (6): A SCPI-Based HPIB Instrument -- The 34401 DMM

* This chapter illustrates the implementation of SCPI by showing how it is implemented in a practical instrument, the popular 34401 digital multimeter (DMM), known informally as the "Alf".

Due to its relative simplicity and wide range of functionality, the Alf is an excellent demonstration of a SCPI-based instrument. This chapter will outline the functionality of the DMM, describe its SCPI command set, and provide short programming examples of its use.



BACK TO INDEX

[6.1] 34401 OVERVIEW

* The 34401 DMM has the following measurement capabilities:

Both HPIB and RS-232 interfaces are standard for remote programming and for direct printer output. The RS-232 output can be modified to provide a digital pass-fail output.

The Alf features a SCPI-based command set (with some extensions for features not included in the SCPI standard at the time the DMM was designed), plus the ability to emulate the HP 3478A DMM or the Fluke 8840A/8842A DMM.

Note that the 34401 was described as having "relative" simplicity. Due to its wide range of capabilities, there is still a lot of detail to consider. These capabilities are broken down into the following categories:

* The DMM's measurement configuration features include the following:

* There are five math operations, only one of which can be enabled at a time. Each performs a mathematical operation on each reading, or stores data on a series of readings. The math operations use one or more internal registers, while others hold the results of the math operation.

The table below shows the allowed math / measurement function combinations:


   ___________________________________________________

             Null    Min-Max    dB       dBm     Limit  
   ___________________________________________________

   DC V        X        X        X        X        X    
   AC V        X        X        X        X        X    
   DC I        X        X                          X    
   AC I        X        X                          X    
   OHMS 2W     X        X                          X    
   OHMS 4W     X        X                          X    
   FREQ        X        X                          X    
   PER         X        X                          X    
   CONT                                                 
   DIODE                                                
   RATIO                X                          X    
   ___________________________________________________
 

Note that only one math operation can be set at a time; setting a new math operation clears the previous one. The operations are as follows:

* The DMM's triggering system allows you to generate triggers manually or automatically, take multiple readings per trigger, and insert a delay before each reading. Normally, the DMM takes one reading per trigger, but you can specify multiple readings -- up to 50,000 -- per trigger.

You can trigger the DMM from the front panel using a single trigger, an external trigger, or auto triggering. Single triggering takes one reading each time you press the "Single" button. External triggering is like single triggering, but the DMM waits for a pulse on the rear-panel EXTERNAL TRIGGER BNC input before taking a reading. Auto triggering takes continuous readings at the fastest possible rate for the current configuration.

Setting up a trigger requires the following steps:

The actions required to perform these steps are outlined below.

* System-related operations include such topics as reading memory, errors, self-test, and display control:

* You can set configuration operations for the DMM's remote programming interface (HPIB or RS-232) from the front panel. Of course it is impossible to do it programmatically. You can also select the DMM's command set. (If you are having troubles communicating with the DMM, you might check to see what interface or language option is set.)

All these configuration settings are stored in non-volatile memory. It will be retained even if the DMM is switched off.

* The DMM allows you to lock out unauthorized calibrations, as well as obtain a count of the number of times it has been calibrated or a message stored during calibration. Of course, this information is stored in nonvolatile memory.

[6.2] PROGRAMMING THE 34401

* The simplest way to obtain a reading from the DMM is via the MEASure? command. However, this command does not offer much flexibility, since the DMM gives you the settings it thinks best for you and then makes the measurement. Optional features, such as setting NULL operation, won't work.

The only settings you can set are function, range, and resolution. You can set these as parameters to the MEASure? command itself:


   MEASure:<function> <range>, <resolution>
 

The relevant functions include:


   VOLTage:DC?               DC voltage.
   VOLTage:DC:RATio?         DC voltage ratio.
   VOLTage:AC?               AC voltage.
   CURRent:DC?               DC current.
   CURRent:AC?               AC current.
   RESistance?               Ohms.
   FRESistance?              4-wire ohms.
   FREQuency?                Frequency count.
   PERiod?                   Period.
   CONTinuity?               Continuity.
   DIODe?                    Diode test.
 

For example:


   100 OUTPUT @Dmm;"MEAS:VOLT:DC? 10,0.003" ! DC, 10 V range, 3 mV resolution.
   110 ENTER @Dmm;Volts
 

For more programming flexibility, use the CONFigure command. This will also preset the DMM to the settings it thinks best, but it won't take a reading; if you want to change some of the settings you may do so, and then take a reading with the READ? command.

READ? will arm the DMM into the wait-for-trigger state. On triggering, the DMM will obtain the reading and place it in the output buffer.

Note that if READ? is used, the output data will not be buffered in internal memory. You have to enter the readings as they arrive in the output buffer or they are lost. Note also that you can provide the same function, range, and resolution parameters for CONFigure that you can with MEASure?

For example:


   100 OUTPUT @Dmm;"CONF:VOLT:DC 10,0.003" ! DC, 10 V range, 3 mV resolution.
   110 OUTPUT @Dmm;"TRIG:SOUR EXT"         ! Trigger on external source.
   120 OUTPUT @Dmm;"READ?"                 ! Wait for trigger and get value.
   130 ENTER @Dmm;Volts
 

The INITiate and FETCh? commands provide the lowest level of control. To read the DMM, you configure it using other commands, and then put it in the wait-for-trigger state with INITiate. Once the DMM has triggered and taken measurements, you can retrieve them with FETCh?; the readings are buffered in internal memory, and FETCh? retrieves them one at a time.

For example:



   100 OUTPUT @Dmm;"CONF:VOLT:DC 10,0.003" ! DC, 10 V range, 3 mV resolution.
   110 OUTPUT @Dmm;"TRIG:SOUR EXT"         ! Trigger on external source.
   120 OUTPUT @Dmm;"INIT"                  ! Wait for trigger.
   130 OUTPUT @Dmm;"FETC?"                 ! Get value.
   140 ENTER @Dmm;Volts
 

This example uses the CONF command to set up the DMM. You can also use the FUNCtion, RANGe, and RESolution low-level configuration commands to perform the precise setup you need:


   100 OUTPUT @Dmm;"FUNC:VOLT:DC"          ! DC volts.
   110 OUTPUT @Dmm;"RANG 10"               ! 10 V range.
   120 OUTPUT @Dmm;"RES 0.003"             ! 3 mV resolution.
   130 OUTPUT @Dmm;"TRIG:SOUR EXT"         ! Trigger on external source.
   140 OUTPUT @Dmm;"INIT"                  ! Wait for trigger.
   150 OUTPUT @Dmm;"FETC?"                 ! Get value.
   160 ENTER @Dmm;Volts
 

There are a wide range of such low-level configuration commands, besides FUNCtion, RANGe, and RESolution:


   NPLCycles              Set number of power-line cycles for a measurement.
   FREQuency:APERture     Set aperture gate time for period measurements.
   PERiod:APERture        Set aperture gate time for period measurements.
   DETector:BANDwidth     Set filter frequency for input signal.
   ZERO:AUTO              Enable or disable autozero mode.
   INPut:IMPedance:AUTO   Enable or disable auto input resistance mode.
 

Each of these commands has a matching query. There is also a query, ROUTe:TERMinals?, to determine if the front or back input terminals are enabled.

* The five math operations are set as follows:


   CALCulate:FUNCtion NULL (default)
   CALCulate:FUNCtion DB
   CALCulate:FUNCtion DBM
   CALCulate:FUNCtion AVERage
   CALCulate:FUNCtion LIMit
 

You can query the function setting with the CALCulate;FUNCtion? query. Once the function has been set, you then have to enable it to get it to operate:


   CALCulate:STATe ON
 

You can disable the math using the OFF parameter instead of the ON parameter. You can interrogate the state with a CALCulate:STATe? query.

You set the parameters for the math operations with the commands listed below. Note that the appropriate operation must be set before setting the parameters:


   CALCulate:NULL:OFFSet
   CALCulate:DB:REFerence
   CALCulate:DBM:REFerence
   CALCulate:LIMit:LOWer
   CALCulate:LIMit:UPPer
 

You can interrogate one of these values from the DMM with the matching query. Finally, you can determine the results for those math operations that return them with:


   CALCulate:AVERage:MINimum?   Gives minimum of min-max operation.
   CALCulate:AVERage:MAXimum?   Gives maximum of min-max operation.
   CALCulate:AVERage:AVERage?   Gives average of min-max operation.
   CALCulate:AVERage:COUNt?     Gives number of values in min-max operation.
 

The following sample program shows how to use the CONFigure command with a dBm math operation:


   10  DIM Ohms(1:5)
   20  ASSIGN @Dmm TO 722
   30  CLEAR 7                            ! Clear HPIB and DMM.
   40  OUTPUT @Dmm;"*RST;*CLS"            ! Reset DMM.
   60  OUTPUT @Dmm;"CALC:DBM:REF 5.0"     ! 50 ohm reference resistance.
   70  OUTPUT @Dmm;"CONF:VOLT:AC 1,0.001" ! Set DMM to 1 amp AC range.
   80  OUTPUT @Dmm;"DET:BAND 200"         ! Select 200 Hz (fast) AC filter.
   90  OUTPUT @Dmm;"TRIG:COUN 5"          ! DMM will accept 5 triggers.
   100 OUTPUT @Dmm;"TRIG:SOUR IMM"        ! Trigger source is IMMediate.
   110 OUTPUT @Dmm;"CALC:FUNC DBM"        ! Select dBm function.
   120 OUTPUT @Dmm;"CALC:STAT ON"         ! Enable math.
   130 OUTPUT @Dmm;"READ?"                ! Get readings, put in output buffer.
   140 ENTER @Dmm; Ohms(*)
   150 PRINT USING "K,1"; Ohms(*)
   160 END
 

* The DMM's triggering capabilities were outlined in the last section. You can generate triggers either manually or automatically, take multiple readings per trigger (up to 50,000), and insert a delay before each reading. To trigger the DMM, you must perform the following steps:

The triggering system is controlled by the following commands:


   INITiate              Set DMM to wait-for-trigger state.
   FETCh?                Get reading from DMM.
   READ?                 Set DMM to wait-for-trigger state, get readings.
   TRIGger:SOURce        Set trigger source.
   TRIGger:DELay         Set trigger delay.
   TRIGger:DELay:AUTO    Enable or disable automatic trigger delay.
   SAMPLe:COUNt          Set number of readings per trigger.
   TRIGger:COUNt         Set number of triggers per reading.
 

Note that all these commands except INITiate and READ? have matching queries. Note also that FETCh?, unlike READ, actually doesn't perform any triggering action, but it is closely related to INITiate, and so is included with the triggering commands.

* The DMM's system-related commands cover a grab-bag of functions, such as display control, beeper control, queries for DMM errors and status, and reset and self-test commands. They include:


   DISPlay               Turn the DMM display on or off.
   DISPlay?              Query the display state.
   DISPlay:TEXT          Display up to 12 characters on the DMM display.
   DISPlay:TEXT?         Query the display text.
   DISPlay:TEXT:CLEar    Clear the message displayed on the front panel.
   SYSTem:BEEPer         Issue a single beep immediately.
   SYSTem:BEEPer:STATe   Disable or enable a front-panel beeper.
   SYSTem:BEEPer:STATe?  Query beeper state.
   SYSTem:ERRor?         Query the DMM's error queue.
   SYSTem:VERsion?       Query the DMM for SCPI version.
   DATA:POINts?          Query the number of readings in the DMM.
   *RST                  Reset the DMM.
   *TST?                 Self-test the DMM.
   *IDN?                 Get DMM ID.
 

* The DMM's status subsystem was discussed in the last chapter. It includes the 488.2 Status Byte and Standard Event register, plus the SCPI questionable data register.

The Status Byte implements four status bits, as listed below. Note that the lowest bit is BIT 0, and that each bit is accompanied by its decimal weight:

The Status Byte is read during a controller serial poll. If the DMM has asserted SRQ, this clears the SRQ and BIT 6. It can also be read with the STB? query. In this case BIT 6 will remain set until it is cleared with a *CLS command.

The Status Byte enable register can be set with the *SRE command and read with the *SRE? query; a set bit will cause an SRQ. The enable register can only be cleared by sending *SRE 0 or by power-cycling, and even with power-cycling, the DMM must have been configured to clear that enable register with the *PSC 1 command before power-down. If *PSC 0 has been sent instead, the enable settings will be retained.

* The Standard Event register implements six status bits:

The Standard Event register can be read with the *ESR? query. Note that this register cannot be written to. The Standard Event enable register is written to with the *ESE command and read with the *ESE? query, and bits set will cause an SRQ, as long as BIT 5 in the Status Byte Enable register is set.

Sending an *ESR? clears the Standard Event register. It is also cleared by the *CLS command. Similarly to the Status Byte enable register, the Standard Event enable register can only be cleared with *ESE 0 or by power-cycling (as long as *PSC 1 has been sent before power-down).

The Operation Complete flag in this register is particularly handy. Using this flag, the controller can initiate a long DMM operation, and then go do something else until the operation completes. When the DMM is done, it will assert an SRQ and interrupt the controller. The controller has to go through the following sequence of steps to implement this scheme:


   100 CLEAR @Dmm                      ! Clear DMM interface.
   110 OUTPUT @Dmm;"*CLS"              ! Clear DMM status registers.
   120 OUTPUT @Dmm;"*ESE 1"            ! Enable OPC event.
   130 OUTPUT @Dmm;"*SRE 32"           ! Enable SRQ on OPC event.
   140 OUTPUT @Dmm;"*OPC?"             ! Send dummy *OPC? to ensure synch.
   150 ENTER @Dmm;Dummy                ! Read back dummy value.
   160 ON INTR 7 GOSUB Handler         ! Set jump to handler routine on SRQ.
   170 ENABLE INTR 7;1                 ! Enable SRQ interrupt for controller.
   180 OUTPUT @DMM;"<command>; *OPC?"  ! Send command, followed by *OPC?.
 

The controller will go on and do other things; when the operation is complete, the DMM will assert an SRQ and cause a jump to the interrupt handler.

* The Questionable Data register implements five status bits:

You can read the Questionable Data register with the STATus:QUEStionable: EVENT? query. This action clears the register. *CLS also clears this register.

The Questionable Data enable register is set with the STATus:QUEStionable: ENABle command. It can be read with the STATus:QUESTionable:ENABle? query. Bits set will cause an SRQ, as long as BIT 5 in the Status Byte Enable register is set. This enable register is always cleared by power-up. It can also be cleared by the STATus:PREset command or by setting it to 0 with STATus:QUEStionable: ENABle 0.

* The calibration commands allow you to perform a calibration of the DMM, determine how many times the DMM has been calibrated, set and query calibration codes, and set and query calibration information. The calibration commands include:


   CALibration?                Perform a calibration.
   CALibration:COUNt?          Get number of calibrations.
   CALibration:SECure:CODE     Set calibration security code.
   CALibration:SECure:STATe    Unsecure or secure for calibration.
   CALibration:SECure:STATe?   Query security state.
   CALibration:STRing          Store calibration data.
   CALibration:STRing?         Read calibration data.
   CALibration:VALue           Set value of calibration reference.
   CALibration:VALue?          Read value of calibration reference.
 

* Finally, to complete the command set, there are three RS-232-only (non-SCPI) commands that perform functions that are inherent to HPIB but not to RS-232:


   SYSTem:LOCal                Put DMM into local state.
   SYSTem:REMote               Put DMM into remote operation.
   SYSTem:RWLock               Put DMM into local lockout.
 

Note that you will not get RS-232 communications to work properly unless you send a SYSTem:REMote command after reset. not

* Error codes are not explained in this document, since a description of the error accompanies the error code returned by the instrument.

[6.3] A SIMPLE 34401 EXAMPLE PROGRAM

* The following HP BASIC example program demonstrates elementary programming techniques for the 34401. It uses a simple text-input menu system to allow you to read AC or DC volts or current, resistance, and frequency, perform test and status operations on the DMM, and clear the display and exit the program. A practical program would be more sophisticated, but this is, after all, an example.


   10    DIM S$[100],P$[100],M$[5],R$[5] ! String, prompt, mode, reply vars.
   20    REAL T                          ! Used for timeout tracking.
   30    INTEGER Sts                     ! Stores serial poll result.
   40    CLEAR SCREEN
   50    !
   60    ON TIMEOUT 7,3 GOSUB Timetrap   ! Set up timeout trap.
   70    ASSIGN @Dmm TO 722              ! Open path to DMM.
   80    ON ERROR GOSUB Errtrap          ! Set up error trap.
   90    !
   100   M$="DC"                         ! Define DC or AC operations.
   110   LOOP
   120     P$="COMMAND:  (M)ode="&M$& / (V)olts / (A)mps"
   130     DISP P$&" / (O)hms / (F)req / (C)ls / (S)ystem / (Q)uit";
   140     INPUT R$                      ! Get reply to prompt.
   150     IF R$="" THEN R$="Z"          ! Check for empty input.
   160     R$=UPC$(R$[1,1])              ! Get first character as uppercase.
   170   ! 
   180     SELECT R$                     ! Test character:
   190   ! 
   200     CASE "M"                      ! Mode:  Toggle mode between DC & AC.
   210       IF M$="DC" THEN
   220         M$="AC"
   230       ELSE
   240         M$="DC"
   250       END IF
   260   !   
   270     CASE "V"                      ! Volts:  Get AC or DC volts.
   280       DISP "Getting volts ... "
   290       IF M$="DC" THEN
   300         OUTPUT @Dmm;"MEAS:VOLT:DC?"
   310       ELSE
   320         OUTPUT @Dmm;"MEAS:VOLT:AC?"
   330       END IF
   340       ENTER @Dmm;S$
   350       PRINT "Voltage value:    ";S$
   360   !   
   370     CASE "A"                      ! Amps:  Get AC or DC amps.
   380       DISP "Getting amps ... "
   390       IF M$="DC" THEN
   400         OUTPUT @Dmm;"MEAS:CURR:DC?"
   410       ELSE
   420         OUTPUT @Dmm;"MEAS:CURR:AC?"
   430       END IF
   440       ENTER @Dmm;S$
   450       PRINT "Current value:    ";S$
   460   !   
   470     CASE "O"                      ! Ohms:  Get 2-wire resistance.
   480       DISP "Getting resistance ... "
   490       OUTPUT @Dmm;"MEAS:RES?"
   500       ENTER @Dmm;S$
   510       PRINT "Ohms value:       ";S$
   520   !   
   530     CASE "F"                      ! Freq:  Get frequency.
   540       DISP "Getting frequency ... "
   550       OUTPUT @Dmm;"MEAS:FREQ?"
   560       ENTER @Dmm;S$
   570       PRINT "Frequency value:  ";S$
   580   !
   590     CASE "C"                      ! Cls:  Clear display.
   600       CLEAR SCREEN
   610   !
   620     CASE "S"                      ! System:  Do system functions.
   630       GOSUB System
   640   !
   650     CASE "Q"                      ! Quit program.
   660       DISP "Done!"
   670       STOP
   680   !
   690     CASE ELSE                     ! Bogus input.
   700       INPUT "ERROR:  Bad command.  Press enter to continue.",R$
   710   !
   720     END SELECT
   730   END LOOP
   740   !
   750 System: !                           Perform system commands.
   760   LOOP
   770     INPUT "COMMAND:  (C)lear / (I)d / (T)est / (E)rror / (R)eturn",R$
   780     IF R$="" THEN R$="Z"          ! Test for empty input.
   790     R$=UPC$(R$[1,1])              ! Get first character as uppercase.
   800   !
   810     SELECT R$                     ! Test character:
   820   !
   830     CASE "C"                      ! Clear DMM.
   840       DISP "Clearing DMM ... "
   850       CLEAR @Dmm
   860       OUTPUT @Dmm;"*RST;*CLS"
   870       PRINT "Reset complete!"
   880   !  
   890     CASE "I"                      ! Get ID string.
   900       DISP "Getting ID ... "
   910       OUTPUT @Dmm;"*IDN?"
   920       ENTER @Dmm;S$
   930       PRINT "Dmm ID string: ";S$
   940   !  
   950     CASE "T"                      ! Self-test DMM.
   960       DISP "Testing ... "
   970       OUTPUT @Dmm;"*CLS;*ESE 1;*OPC?" ! Flag OPC when test over.
   980       ENTER @Dmm;S$
   990       OUTPUT @Dmm;"*TST?;*OPC"    ! Test, flag OPC.
   1000      T=TIMEDATE                  ! Get initial time.
   1010      LOOP
   1020        Sts=SPOLL(@Dmm)           ! Spoll for ESB (=OPC) bit.
   1030      EXIT IF BIT(Sts,5)=1
   1040      EXIT IF TIMEDATE-T>30       ! Keep checking for 30 seconds.
   1050      END LOOP
   1060      IF BIT(Sts,5)=1 THEN     
   1070        ENTER @Dmm;S$
   1080        PRINT "Test status: ";S$
   1090      ELSE
   1100        PRINT "Test timed out!"
   1110      END IF
   1120  !  
   1130    CASE "E"                      ! Get error status.
   1140      DISP "Getting error status ... "
   1150      OUTPUT @Dmm;"SYST:ERR?"
   1160      ENTER @Dmm;S$
   1170      PRINT "Error status: ";S$
   1180  !
   1190    CASE "R"                      ! Return to main.
   1200      RETURN
   1210  !  
   1220    CASE ELSE                     ! Bogus input.
   1230      INPUT "ERROR:  Bad command.  Press enter to continue.",R$
   1240  !  
   1250    END SELECT
   1260  !
   1270  END LOOP
   1280  RETURN
   1290  !
   1300 Timetrap: !                        Trap timeout error.
   1310  INPUT "ERROR:  Timeout -- press Enter to continue.",R$
   1320  ERROR RETURN
   1330  !
   1340 Errtrap: !                         Trap error.
   1350  PRINT ERRM$                     ! Print error string.
   1360  INPUT "ERROR:  Press Enter to continue.",R$
   1370  ERROR RETURN
   1380  !
   1390  END
 

[7.0] HPIB Tutor (7): Notes & Comments

* This last chapter covers a few interesting topics in HPIB not easily discussed elsewhere.



BACK TO INDEX

[7.1] BENCHMARKS

* There is an old saying that there are lies, damn lies, and statistics, to which a modern wit added "damn statistics" ("four out of five doctors recommend"), then "benchmarks". To this I add: "damn benchmarks".

Benchmarking is a confusing topic where one is given a very specific value whose real relationship to what he or she actually wants to know is no more than an approximation, subject to a number of conditions.

This is, as shall be explained, inevitable, so the important question is one of what constitutes "benchmarks" (honestly-stated information) and what constitutes "damn benchmarks" (meaningless hype), and how one can tell the difference.

* In the case of HPIB, there are a lot of benchmarks and damn benchmarks out there. Customers often want to get estimates for the performance (in kilobytes per second) they can expect to obtain for an HPIB application with a specific HPIB card. There are two types of benchmarks that need to be provided in response: "typical" performance figures, and "maximum" performance figures.

Typical performance figures are usually obtained by setting up the PC and a low-cost instrument (the HP 34401 "Alf" DMM is currently popular for this task) and then simulating a typical customer application.

This sounds simple enough, and it is, but the complexity comes in considering what information you're getting out of it. The performance of the system will depend on four factors:

In practice, such a typical benchmark says almost nothing about the performance of an HPIB card, since almost any HPIB card you could buy would be able to keep up with the actions of the system. The speed will be far more determined by the PC and the design of the program, since the data transactions over HPIB are a small part of the total. The typical benchmark is useful in that it provides a minimum value that the user can expect to obtain.

* The maximum performance benchmark is where things get more interesting. In this case, the benchmark is optimized for the maximum possible performance to provide an upper limit on HPIB card operation.

The four constraints outlined for the typical benchmark above apply in the maximum performance benchmark case as well, but with added subtleties:

The maximum-performance benchmark actually does reveal true facts about the HPIB card, but it is made under constrained and specific circumstances, and except in providing an upper limit, only gives specific information when the test conditions are fully known.

Note that some vendors are promoting HPIB card with supposed enhanced-performance features. The catch is that such enhanced performance is only available under specialized circumstances (as above) and with instruments that also support the same enhanced-performance spec, and which are few in number these days. There is a need for a faster instrument interface than HPIB, but it will probably be derived from new high-speed serial buses and the like currently being implemented on PCs.

* In summary, when you ask for benchmark figures, you will need to know what you are asking for and what you can expect. What most users want to know is: "How fast can my application run?" Without implementing the application, nobody can say. All that can be done is give an estimate of limits and constraints.

Realistic benchmarks will provide both typical and maximum performance figures, with an outline of what the benchmark programs do and the necessary details, such as the type and configuration of PC, the programming language used, the instrument used in the test, and so on. Any reasonable benchmark will also clearly state that there is no guarantee that a specific application will obtain the same figures, since the specific performance only relates to the benchmark test itself.

In marketing copy, it is hard to point out these details, so you should assume that if you are given a performance figure without comment it is a maximum figure and obtained under optimum circumstances. Really impressive performance figures (some vendors quote a "megabyte per second", which is the theoretical limit to HPIB transfer rates) should be regarded with suspicion as "damn benchmarks" since they were probably put together using unrealistic assumptions.

In practice, actual performance is a system issue, and will be determined by the user's knowledge of all system elements -- PC configuration, program design, HPIB optimization, and instrument operation. A fast HPIB card counts for very little if the application is dumping data to a bottleneck like a tape drive. But having realistic benchmarks for any one element will tell you what is, and what is not, possible.

[7.2] PASS CONTROL & NON-CONTROLLER OPERATION

* Some HPIB programmers attempt to write programs that assume non-controller operation. They want to either temporarily pass control to another controller, or operate as a pure slave (talk-listen-but-not-control) device They find they run into difficulties.

While passing control is straightforward, it does require a good understanding of how the HPIB protocols (and the interface library that implements them) work. However, operation as a slave is much trickier and very difficult to implement in a reliable fashion.

This problem is compounded by the fact that many interface libraries implement pass-control or slave-operation features in a slipshod fashion, and often have not tested what they have implemented in any methodical way. For these reasons, it is strongly recommended that passing control not be done unless there is no other way to do the required task, and that slave operation be avoided if at all possible.

Nonetheless, if you are forced to deal with these matters, hear are some clues and hints. Since HP BASIC for stand-alone workstations has the most robust HPIB implmentation I know of, the discussion is purely based on HP BASIC commands. You will need to find analogous commands on your target system, though it is likely the implementation will not be anywhere near as good.

The following discussion necessarily repeats information provided in a more terse fashion in earlier chapters for the sake of coherence.

* If you have multiple controllers on the same HPIB, one will be the system controller and all the others will be non-system controllers. On traditional HP BASIC workstations, this is set with a DIP switch.

The first visible distinction between the two is this: when you power up the controllers, the system controller will come up by default operating as a controller -- that is, you will be able to communicate with instruments -- while the non-system controllers will be operating by default as slaves -- that is, they will not be able to address any devices on the HPIB.

This means that if you perform:


   OUTPUT 705;"*IDN?"
 

-- on the system controller, it will work fine (assuming that there is a device with address 705 out there on the HPIB), but if you do it with a non-system controller, you'll get an error message:


   ERROR 173  Active/system controller req'd
 

Some users set up a non-system controller, get this error message, and think it's a bug. No, it's doing what it's supposed to be doing.

Now suppose you put these two controllers on the same HPIB and wish to pass control between them. The first issue is one which is often forgotten by HPIB users: that a controller has an HPIB address, just like an instrument (the default controller address for an RMB workstation is 21), and you can't have two devices on the bus with the exact same address.

Fortunately, you can set a controller to another HPIB address by writing to HPIB status register 3:


   CONTROL 7,3;1   ! Set interface 7 to HPIB address 1.
 

I assume the HPIB is at interface select code 7, a convention that I will stick with in the rest of the discussion. I usually prefer to set the non-system controller to address 1 and leave the system controller to address 21.

Given this knowledge, it is perfectly easy to pass control from the system controller to the non-system controller with:


   PASS CONTROL 701    ! Sends TCT (Take ConTrol) byte.
 

The non-system controller can then pass it back with:


   PASS CONTROL 721
 

* Seems pretty simple, right? Well, it is simple, but not quite that simple. There's a few other details to consider. that

The first detail can be phrased as a question: how does an RMB program know if it's running on a system controller or nonsystem controller, or if it is the current active controller? Without this knowledge, the ability to pass control will lead quickly to mutual confusion within the programs on the two systems.

This is pretty straightforward, with that information provided by status register 3. Bit 7 says if the controller is a system controller (1) or non-system controller (0) and bit 6 says if the controller is the active controller (1) or inactive controller (0):


   STATUS 7,2;Sts
   IF BIT(Sts,7)=1 THEN
     PRINT "System controller."
   ELSE
     PRINT "Non-system controller."
   END IF
   IF BIT(Sts,6)=1 THEN
     PRINT "Active controller."
   ELSE
     PRINT "Inactive controller."
   END IF
 

Note that the five lowest bits of status register 3 also give the HPIB address of the controller:


   PRINT "HPIB Address =";BINAND(Sts,31)  ! Print lowest five bits.
 

Anyway, this status is essential for avoiding confusion in controller-noncontroller operation.

* The second detail concerns the actual protocol for passing control. To be sure, if one controller passes control to a second controller, the second controller becomes active controller without any further trouble, but usually the inactive controller is the one driving the process, since it wants to do something and the active controller is in the way.

So the inactive controller can assert an SRQ -- service request -- using the REQUEST statement to ask the active controller to pass control:


   REQUEST 7,64
 

Note that only the interface select code is specified. Naturally, since all this does is assert the SRQ line and make a serial poll response byte (here given as 64) available. A value of 64 sets bit 6, which indicates a service request. Setting any other bits is optional.

The active controller will then perform serial polls to see who asserted the SRQ. If it's the inactive controller, it then passes control:


   STATUS 7,7;Sts                
   IF BIT(Sts,10)=1 THEN    ! SRQ bit is bit 10 of HPIB status 7.
     Sts=SPOLL(701)         ! Serial poll inactive controller.
     IF BIT(Sts,6)=1 THEN   ! If SRQ bit set, then pass control.
       PASS CONTROL 701
     END IF
   END IF
 

This code sample assumes operation on the system controller. Note that this sample actually checks the SRQ bit in status register 7 to see if an SRQ has happened. In reality, it may be easier to do it using an interrupt:


   ON INTR 7 GOSUB Srqtrap    ! Set up jump.
   ENABLE INTR 7,2            ! Specify SRQ interrupt.
   ...
 Srqtrap: !
   Sts=SPOLL(701)
   IF BIT(Sts,6)=1 THEN
     PASS CONTROL 701
   END IF
   RETURN
 

* The third detail is that the system controller can, unlike all the other controllers on the same HPIB, get control back any time it wants it, by executing the command ABORT, which asserts IFC (interface clear) and restores all the interfaces to their default state.

* The distinction between the concepts of system controller and active controller should be clearly described by the discussion so far, but since this is a confusing issue let me summarize it.

There can be multiple controllers on a single HPIB connection. Any of them can be active controller if control is passed to them. There is, however, only one system controller. It comes up as active controller on boot-up (the non-system controllers are inactive on boot-up), and it can take control back from any other controller by executing ABORT.

The system controller is not necessarily the active controller. The active controller can jump from controller to controller as control is passed over the bus. But it is always the system controller, and it is the only system controller.

* This explains about all there is to know about passing control in itself, with the exception of one final detail: why do it?

The only good reason that I know for passing control is that instruments often have the capability to dump a plot to a plotter or printer on the same HPIB. Some of the older instruments will demand to be made system controller for this operation. The program sends it a command to print, passes control to it, then wait for it to pass control back.

However, it is a common misconception that this is the only way to perform this task. The logic is that the instrument is talking to the printer or plotter, and of course it has to be a controller to do that, right?

No, not really. A controller can set up one device as a talker and another as a listener, and then the two can talk to each other without controller intervention. Assuming an instrument at address 713 and a printer at address 705, most instruments that have the capability to dump directly to a printer could be instructed to do so with something like this:


   OUTPUT 713;"PRINT?"
   SEND 7;UNT UNL TALK 713 LISTEN 705 DATA ""
 

The SEND command sends HPIB command bytes, setting up the talker-listener transaction (the DATA "" at the end releases the ATN line, allowing the transaction to proceed).

Of course, if the instrument understands the 488.2 OPC? (operation complete) query, the program can also instruct it to assert an SRQ when it is done with the print operation. However, that is a little beyond the scope of this discussion.

* So passing control can be done easily, but in general it's not all that useful. What is not so easy to do is try to write an RMB program that operates completely in noncontroller mode -- that is, just like an instrument on the HPIB, its operations directed by the controller.

Using an HPIB controller is easy. It tells the other devices what to do whenever it pleases, and they have to respond accordingly. For this reason, being an HPIB slave is hard. It has to respond whenever required, with the information the controller expects to get back.

This normally means that you have to set up an interrupt in the noncontroller so it can respond when needed. The most useful interrupt for this purpose is the "talker-listener address change" (TLAC) flag associated with the interface, which is asserted any time the slave is addressed. An interrupt on TLAC can be set up as follows:


   ON INTR 7 GOSUB Tlacintr
   ENABLE INTR 7;256
 

When the slave gets the TLAC interrupt, it can then check to see if it is addresses to talk or listen and respond accordingly:


 Tlacintr: !
   STATUS 7,6;Sts
   IF BIT(Sts,10)=1 THEN       ! Addressed to listen (LADS).
     ENTER 7;S$                ! Get a command (I/O is from interface).
     ELSE
     IF BIT(Sts,9)=1 THEN      ! Addressed to talk (TADS)
       SELECT S$
       CASE "*IDN?"
	 OUTPUT 7;Addrstr$     
         ...
       END SELECT
     END IF
   END IF
 

Note that status register 6 contains the listen-addressed (LADS) bit (bit 10) and the talk-addressed (TADS) bit (bit 9), and that the ENTERs and OUTPUTs have to be from the interface (remember, only a controller has addressing privileges).

This is a pretty rough outline of what needs to be done, however. The slave must actually be able to respond precisely to whatever the controller asks of it using the list of CASE statments above. The protocol for doing this has to be agreed-on by the controller and slave.

This is not too hard if the controller just sends a command and the slave makes a response. The slave's operation would look something like this:


   get TLAC interrupt
   slave is listen addressed
   get and check command
   go back to wait on TLAC interrupt

   get TLAC interrupt
   slave is talk addressed
   provide proper output for command
   go back and wait on TLAC interrupt
 

The slave has to do a lot of error checking, however. If anything goes wrong, it needs to issue an error and then go back and wait for the controller to issue a new command it understands.

Where this gets really tricky is when you want to transfer, say, a file of indeterminate length between the controller and slave. Once the slave has been given the command to send a file and is then addressed to talk, it then must sit in a loop and send the file line by line and assume the controller is reading it, since the slave remains in talk mode until otherwise instructed. On the last line, the slave needs to assert EOI with the last byte to tell the controller that the transmission is over. Similar comments apply to transferring a file from the controller to the slave.

This may sound straightforward, but in practice it can be a real nuisance to get to work. RS-232, which is a peer-to-peer system, for once works better than HPIB.

In summary, once more: you don't want to try to do things like this if you have any choice in the matter. Under RMB it is tricky. Under other applications and interface libraries, it may be completely impossible.