Chem 498A/C: Electronics and computer Interfacing in Chemistry. Fall 1997

Introduction to QuickBASIC
(IBM-PC and Mac versions)

RETURN to the CHEM 498C Home Page

BASIC, which stands for Beginner's All-purpose Symbolic Instruction Code, is an easily-learned computer language that was developed in the 1960's. It is still important because of its adoption by the influential industry giant MicroSoft as the basis for their Visual Basic language and of the macro language in version 5 of their Excel spreadsheet (VBA, Visual Basic for Applications). The brief introduction here is based on a simple BASIC dialect called QuickBASIC.

Go through each of the commands and sample codes described here to verify that they work as you expect. Then do the assignment at the end and submit printed program listings.

1. Control commands and editing.
IBM-PC (DOS). Run QuickBasic by typing qb at the DOS prompt and press ENTER. This takes you to the editor window. When you write a program from scratch, you type in program lines, using the cursor keys (or the mouse if there is one on your computer) to navigate around in the text, the delete key to erase text. To save your program, press ALT-F and then S, type a file name and press RETURN. To load an existing program, press ALT-F and then O. This presents a list of files in the QuickBasic subdirectory. Press Tab to move to the file list, use the cursor keys to select the desired file and then press RETURN to load it. To execute (run) the program press Shift F5. F4 toggles between output window and editor screen. F6 toggles between command window and editor screen.

Mac. Launch QuickBasic by double-clicking on the QuickBasic icon. The screen shows three windows: the output window (where program-generated output goes), the editor window (where you type and edit programs), and the command window (where you can type and execute single commands instantly). The editor window works just any Mac (or Windows) text editor, with Open and Save commands, Copy and Paste, etc. To run a program, hold down the apple key and press R. To stop a running program, hold down the command (apple) key and type a period. To bring up the editor window, press (apple)-L. To print the program listing, select Print from the File menu.

2. Text Screen printing. PRINT A prints the value of the variable A on the screen and moves the cursor to the next line. Putting a semicolon at the end of the line keeps the cursor on the same line. The default output screen has 24 lines and 80 columns. CLS clears the text screen. LOCATE y,x moves the cursor to the line y, character position x.

3. Keyboard input. INPUT A$ pauses the program, displays a ? prompt, waits for any string of characters to be typed in, then when is pressed, assigns the string variable A$ to the string typed in. To read the keyboard on the fly, without pausing the program, use key$=INKEY$, which assigns the last key pressed to the string variable key$. This is useful in real-time control applications, to allow a program to continue to run while it checks for keypresses.

4. Data Types and labels . Variables can be given alphanumeric names, i.e. pH, volume1,volume2, etc., but reserved words (the names of BASIC commands and functions) can not be used for variable names. String variables have a $ added (i.e. reply$) and are limited to 255 characters. Integer variables have a % (i.e. reading%) and must be between -32767 and 32767. Real (floating point) numeric variables nave no suffix and have a range of 1038. Arrays of reals, integers, or strings are indicated by (). Thus DIM A%(1000) dimensions (allocates space for) an array of 1000 integer numbers. LET Z%=A%(K) sets Z% equal to the Kth element of the integer array A%(). Arrays of reals and strings are handled the same way.

After a program has been run once, you can interrogate the current value of any of its variables by switching to the command window and typing ? followed by the name of the variable. This is a useful technique in troubleshooting.

5. Functions and math statements. BASIC uses the same sort of "computer math" notation as most other languages and spreadsheets, etc, with +, -, *, and /, parentheses for grouping, ^ for exponents. The principal math functions are SQR() (square root), EXP(), LOG() (natural log), SIN(), COS(), TAN(), RND() (a random number between 0 and 1).

6. Loops and Decisions. To execute a number of statements a fixed number of times, use a FOR/NEXT loop:

FOR X=1 TO 10
    PRINT X, SIN(X)
NEXT X

which causes the line or lines between the FOR and the NEXT to be executed repeatedly for every value of X from 1 to 10. To create a loop that executes until some condition occurs or while some conditions exists, use the WHILE... WEND construct. For example, this is useful for reading a text file of unknown length until all data are read:

OPEN "data.txt" FOR INPUT AS #1
k = 0
WHILE NOT EOF(1)            
  INPUT #1, Y(k)                 
  k = k +1              
WEND 

The statements between the WHILE and the WEND are executed repeatedly as long as the condition NOT EOF(1) is true. In this case the condition is the boolean function EOF, which returns a true when the end of the file is reached. Conditions can also be boolean expressions such as x=1 or a>b, containing any combination of variables, constants or expressions related by = (equal), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), <> (not equal to). You can also combine conditions using AND or OR: e.g., X > 0 AND X < 100.

For simple two-way decisions, use the IF clause:

IF y<0 THEN
    PRINT "Y is negative"
  ELSE
    PRINT "Y is not negative"
END IF

For multiple choice situations, use the CASE structure:

SELECT CASE K$
  CASE "A","a"
    PRINT "K$ was A"
  CASE  "B","b"
    PRINT "K$ was B"
  CASE ELSE
    PRINT "K$ was neither A nor B"
END SELECT

To jump directly to another line in a program, use a GOTO aaaa statement and label the line to jump to with aaaa: placed first in the line. For example:

TryAgain: INPUT "Pick a number between 1 and 10", A
IF A < 1 OR A > 10 THEN GOTO TryAgain 

7. Subroutines and subprograms. Subroutines and subprograms are sections of a program code that are set apart from the main program so they can be called from several places in the main program and which, after they are finished, return to the next line in the main program. They are most commonly used for code which is re-used several times in one program. A subroutine begins with a labeled line and ends with a RETURN statement. It is called with a GOSUB command. All of the variables in a subroutine are global, that is, they are shared with the main program. A subprogram, on the other hand, begins with a SUB statement and ends with an END SUB; it is called with a CALL statement. All of the variables in a subprogram are local, that is, they are independent of the variables in the main program. Information is passed between the subprogram and the main program by means of an argument list.

8. Memory access and Input and Output ports. Laboratory interfacing using add-in cards (e.g. analog-to-digital and digital-to-analog converters) usually requires direct access to absolute memory locations. On the IBM-PC, access to add-in boards is by means of special input and output instructions that refer to I/O ports. To output to an I/O port, you use OUT port,datum, where port is the output port number (range: 0-65535) and datum the single-byte integer data value (range: 0-255). To get input from a port, you use the INP function: datum = INP(port), where port is the input port number (range: 0-65535) and datum a single-byte integer data value read from the port (range: 0-255). The port number is usually determined by switch settings on the add-in card.

9. Data files. It is often necessary to save and recall data (e.g, a spectrum, chromatogram, titration curve, etc.) as a disk file. Such data are often stored in the computer's memory as an array. The simplest way to store data on the disk is as a sequential text file, which stores the ASCII text as they would be printed out on the screen or printer. Each data number can take anywhere from 2 bytes (e.g. an single-digit number follower by a carriage return) to 15 bytes (e.g. -1.4354557E-10) for a single-precision real. For example, this program creates a sequential text file named "SEQFILE.DAT" containing 100 x-y pairs where x = 1 to 100 and y = square root of x:

OPEN "SEQFILE.TXT" FOR OUTPUT AS #1
FOR j = 1 TO 100              
  WRITE #1, j, SQR(j)         
NEXT j                                 
CLOSE #1

This program reads and prints out the contents of the file "SEQFILE.DAT":

OPEN "SEQFILE.TXT" FOR INPUT AS #1
FOR j = 1 TO 100               
  INPUT #1, x, y              
  PRINT x, y                  
NEXT j                        
CLOSE #1 

10. Printing to the network printer from with a program. On the Macintosh, program output may be directed to the currently-selected printer on the LocalTalk network by opening the printer like it were a file. At the beginning of the program, you assign a file channel to the printer:

OPEN "LPT1:PROMPT" FOR OUTPUT AS #1 

Later in the program when you are ready to print, say, the variable Z$, use PRINT #1, Z$. At the end of the program, CLOSE #1. Use a channel number different from other open files.

11. Graphics. On an IBM-PC you have to use the SCREEN command to specify the screen mode. The old PC-XTs have GCS graphics, which calls for the use of the SCREEN 1. The graphics screen coordinates are 0 to 320 on the horizontal (X) axis and 0 to 200 on the vertical (Y) axis. The newer models have VGA graphics; use SCREEN 12. The graphics screen coordinates are 0 to 640 on the horizontal (X) axis and 0 to 480 on the vertical (Y) axis.

On the Macintosh, the SCREEN command is not used; the graphic screen coordinates depend on the size of the output window - typically 0 to 620 on the horizontal (X) axis and 0 to 430 on the vertical (Y) axis.

The origin (0,0) is on the upper left. PSET (X,Y) plots a point at X,Y. LINE (X1,Y1) - (X2,Y2) draws a line from coordinates X1,Y1 to X2,Y2. In DOS, attempting to plot outside of the allowed coordinate range results in an error message (but not on the Mac).

Axis labels and other text notations to a graphic screen are easily added by using the LOCATE and PRINT commands.

12. String operations. BASIC was the first language to have a set of string manipulation functions. Try these out so you understand their function.

These functions are very useful in interfacing applications, for example to construct command strings for the automation of an RS-232-interfaced instrument, to process received data strings from such an instrument, to construct algorithmically generated filenames, and to process user input from the keyboard. Here's an example of the last application. Often, within a program, it's necessary to give the operator some way of changing specific variables. The following example displays the current value of the variable X1 and allows the user to change it by typing in a new value and pressing or to leave it alone by simply pressing .

PRINT "Value of variable X1 (currently ";X1;")";
INPUT A$
IF A$<>"" THEN LET X1=VAL(A$)

From a user interface point of view, it is better to enter numeric data this way, rather than using INPUT X1. The latter will give an error message and abort the program if any non-numeric entry is made, whereas INPUT A$ will accept any string, even an "empty" RETURN. VAL simply returns a zero for any non-numeric input, but this can be easily checked for by the program. The VAL function also strips off any trailing alphabetic characters (e.g. units, etc.)

Assignment

1. Write a program that calculates one complete cycle of a sine wave (from 0 to 2) and saves it as a sequential text file in x,y format (on the boot disk). Use a text editor to open and inspect the resulting data file. Submit a printed program listing.

2. Write a program that reads a sequential text file in X,Y format (up to 100 data pairs in length), determines the number of data pairs and the range of X-values and Y-values, and plots all of the X,Y pairs as points on the graphic screen so that Xmin is near the left of the screen, Xmax is near the right of the screen, Ymin is near the bottom of the screen, and Ymax is near the top of the screen. Draw and label the X- and Y axes. Test this program on the file generated in part 1. Submit a printed program listing.


This page is maintained by Tom O'Haver , Department of Chemistry and Biochemistry, The University of Maryland at College Park. Comments, suggestions and questions should be directed to Prof. O'Haver at to2@umail.umd.edu.