ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 15.06.2025

Просмотров: 2085

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Programming

Subroutines have two advantages. First, they help you to break up your program code into discrete units, with each having a specific purpose. This makes the program code easier to debug and easier to understand in general, especially if you return to it a week, month, or year after writing it when the details are no longer fresh in your mind. Second, subroutines make it easier to reuse your code if you have a similar task in another project. For example, all or most of the code involved with controlling a display module can usually be written as a subroutine, or perhaps a series of subroutines. This way, if you want to use the same display module in more than one project, you can reuse the code without having to pick through your previous programs to find the program lines that you need.

Keep program lines short. Short lines are easier to edit with BASIC-52’s line editor, which requires retyping the entire line to make a change. They’re also easier to read. If you upload programs from disk, shorter lines can eliminate problems caused by BASIC-52’s not having enough time to process each line before the next one arrives. Although BASIC-52 allows you to place multiple statements on one line, with up to 79 characters per line, shorter is better.

There are two situations where you might want to combine a series of short lines into fewer, longer program lines: when the program has to execute as fast as possible, or when you need to store the program in the smallest possible space. Even then, though, you can develop the program with short lines, and combine them only after the program is debugged and ready for permanent storage.

Check syntax and spelling carefully. BASIC-52’s syntax consists of the rules of grammar and punctuation that your program lines must follow. For example, a FOR loop must include a variable, limits, and a NEXT instruction. Leave any of these out, and your loop won’t work. There’s no room for spelling errors either. BASIC-52 doesn’t know that you meant LIST when you typed LSIT.

Document your programs. Many of BASIC-52’s keywords aren’t too hard to decipher. For example, it makes sense that the STOP instruction halts program execution. But your own comments throughout the program can help you remember why you wrote each program line, and what it’s supposed to accomplish.

BASIC-52 allows you to add comments, preceded by REM (remark). Try to write comments that do more than just define the keywords in the line. Also explain the purpose behind what you are doing. For example, this comment

10 REM read value from external memory

20 A=XBY(0FE00H)

does nothing more than define the BASIC-52 instruction that follows. In contrast,

The Microcontroller Idea Book

67

Chapter 5

10 REM Read the states of switches 1-8 20 A=XBY(0FE00H)

tells you why you are executing the instruction.

The problem with adding comments to BASIC-52 programs is that they slow program execution. They also make the program longer, so that it needs more memory. So you might want to keep comments to a minimum in the final version that you store in NV memory.

You can, however, store fully documented copies of your program on disk. If you wish, you can use your personal computer’s text editor to add comments on unnumbered lines, like this:

REM Read the states of switches 1-8 20 A=XBY(0FE00h)

Then, as you upload the program to your 8052-BASIC system, all of the lines will display on the host computer, but BASIC-52 will store only the numbered lines, discarding the unnumbered remarks.

Use short variable names for faster execution speed. BASIC-52 allows variable names of up to eight characters. Programs with shorter variable names will run faster and require less memory to store. Even if you limit yourself to 1- and 2-letter variables, you still have hundreds to choose from. Longer names, such as REVERSE, QUIT, and so on have the advantage of being more meaningful—it’s easier to guess their meaning without adding comments. So there are times when you might choose a longer name. But longer names can cause other problems, as the next paragraph explains.

Be sure that variable names don’t contain keywords. In BASIC-52 you can’t name a variable ON, because ON is already defined by BASIC-52. You also can’t name a variable MONTH, ONE, ACTION, or any other word that contains ON. Short variable names are much less likely to contain an embedded keyword. Also be aware that BASIC-52 identifies a variable only by its first and last characters, plus its length, so, for example, it considers MAXIMUM and MINIMUM to be the same variable, while MAX and MIN are different.

Avoid variables that begin or end with the letter F. BASIC-52 has a couple of bugs relating to variable names that begin or end in F. Specifically, when F is the last character in a variable name followed by a space, BASIC-52 drops the F from the variable name. And, if you should name a variable FP, FPR, or FPRO, and follow the name by a space, BASIC-52 will also drop the F from the name. The easiest way to avoid problems is to avoid any variable name that begins or ends in F.

68

The Microcontroller Idea Book


Programming

Hexadecimal numbers that begin with A through F must have a leading 0, and all hexadecimal numbers must end in H. Here are some examples of valid hexadecimal numbers:

Valid Hex Number

Decimal Equivalent

0DH

208

0AH

10

15H

21

0FFFFH

65,535

0CH

12

Here are some invalid hex numbers, and a valid hex number that doesn’t have its intended value:

Invalid Hex Number

Problem

FFH

no leading 0

0C

no trailing H

10 (intended as decimal 16)

no trailing H. BASIC-52 will interpret at

decimal 10 (0AH)

BASIC-52 Bugs and Things to Watch Out For

This section is a summary of other bugs and other minor problems with BASIC-52 to be aware of as you program. Many of BASIC-52’s bugs and limits have been eliminated in newer versions of BASIC-52 developed by other sources, described in Chapter 15.

Assembly-language Issues:

In external code memory, if 2002h contains 5Ah and bit 5 at 2048h is set, BASIC-52 will try to call a user-written token table. If 2001h contains 0AAh, BASIC-52 will try to call a user-written reset routine at 2090h. If the expected table or routine isn’t present, the system will crash. (See Chapter 13.) Solution: avoid writing to code memory at 2001h, 2002h, and 2048h. (In Figure 3-1’s circuit, the RAM in this area (if any) is accessed as data memory only, so you don’t have to worry about this.)

The Microcontroller Idea Book

69


Chapter 5

The address following a CALL instruction must be at least 2000h.

Miscellaneous Items:

Floating-point calculations have errors when the numbers are very large or very small.

The value returned for the ASC(character) operator is incorrect for these seven characters:

+ - = . ? / *

ONTIME and ONEX1 will not cause interrupts during an INPUT statement. User delay in responding to an INPUT may cause the program to miss interrupts.

Finding Program Errors

Writing a program that does what you want isn’t always easy. A single missing character or program line can cause a program to stop in its tracks, or continue to execute but with unintended results, or, worst of all, crash the system and require rebooting.

BASIC-52 will detect and warn you of many programming errors. If BASIC-52 detects an error when you try to run a program, it will display the line containing the error, along with an error message, and will stop the program at that point.

If you get an error message, examine the offending line carefully. Many problems are due to syntax errors, where missing or incorrect characters make it impossible for BASIC-52 to interpret the program line correctly.

Other times, a program will run without problems, but it won’t do what you intended. For example, it’s easy to forget that a hexadecimal number beginning in A-F must have a leading zero, or that all hexadecimal numbers must end in H. Each of these BASIC-52 statements has a different result, and none will produce an error message:

BASIC-52 Statement

Resulting Action

XBY(1000H)=20H

Writes 20H

to 1000H in external data memory

XBY(1000)=20

Writes 14H

to 3E8H in external data memory

XBY(1000H)=20

Writes 14H

to 1000H in external data memory

XBY(1000)=20H

Writes 20H

to 3E8H in external data memory

70

The Microcontroller Idea Book

Programming

It can be hard to find an error that gives no error message. The best way to narrow the search is to write and test your programs in small modules, so that the amount of code to search through remains manageable.

The Microcontroller Idea Book

71

Chapter 5

BASIC-52 Keywords by Function

The following is a quick reference to BASIC-52’s keywords, grouped by function. After this is a more detailed list, arranged alphabetically, with the syntax and a brief description of what each keyword does. Some of the keywords, like RUN, LIST, and PRINT, are ones that you’ll use constantly. A few, like NULL or UI0, have specialized uses that you may never need. Again, for a more complete reference, see the BASIC-52 programming manual.

Running and Listing Programs

CONT

LIST

NEW

RAM

REM

ROM

RROM

RUN

STOP

XFER

Storing Programs in NV Memory

FPROG

FPROG1-FPROG6

PGM

PROG

PROG1-PROG6

Program Control Structures

(loops and subroutines)

DO UNTIL

DO WHILE END

FOR TO [STEP] NEXT] GOSUB

GOTO

IF THEN [ELSE] ON GOSUB

ON GOTO

RETURN

Printing and Displaying Information on the Host Computer

PH0.

PH1.

PRINT, P., ?

Additional PRINT Formatting

CR

SPC

TAB

USING, U.

Input/Output

CBY

DBY

GET

INPUT

LIST#

NULL

PORT1

PH0.#

PH1.#

PRINT#, P#, ?#

XBY

System Control Values

BAUD

FREE

LEN

MTOP

STRING

72

The Microcontroller Idea Book


Programming

Math Operators

Data Storage

=

ASC

+

CHR

-

CLEAR

*

CLEARS

/

DATA

**

DIM

>

LD@

<

POP

<>

PUSH

>=

READ

<=

RESTORE

ABS

ST@

ATN

COS

Timers and Interrupts

EXP

INT

CLEARI

LET

CLOCK0

LOG

CLOCK1

NOT

IDLE

PI

IE

RND

IP

SGN

ONERR

SIN

ONEX1

SQR

ONTIME

TAN

PCON

Logical Operators

PWM

RCAP2

.AND.

RETI

T2CON

.OR.

TCON

.XOR.

TIME

Assembly-language Interfacing

TIMER0

TIMER1

TIMER2

CALL

TMOD

LIST@

PH0.@

PH1.@

PRINT@, P@, ?@

UI0

UI1

UO0

UO1

The Microcontroller Idea Book

73


Chapter 5

Quick Reference to BASIC-52

This quick reference to the BASIC-52 programming language lists the keywords alphabetically, along with brief descriptions of function and use.

Conventions

The reference uses the following typographic conventions:

KEYWORDS (boldface uppercase)

BASIC-52 keywords

placeholders (italics)

Variables, expressions, constants, or other information that you must supply

[optional items] (enclosed in square brackets) Items that are not required

repeating elements... (followed by ellipsis (three dots))

You may add more items with the same form as the preceding item.

C = command mode

R = run mode

variable = expression

C,R

Assigns a value to a variable

expression = expression

C,R

Equivalence test (relational operator)

expression + expression

C,R

Add

expression - expression

C,R

Subtract

expression * expression

C,R

Multiply

74

The Microcontroller Idea Book

Programming

expression / expression

C,R

Divide

expression ** expression

C,R

Raises first expression to value of second expression (exponent)

expression <> expression

C,R

Inequality test (relational operator)

expression < expression

C,R

Less than test (relational operator)

expression > expression

C,R

Greater than test (relational operator)

expression <= expression

C,R

Less than or equal test (relational operator)

expression >= expression

C,R

Greater than or equal test (relational operator)

?

Same as PRINT

ABS (expression)

C,R

Returns the absolute value of expression

expression .AND. expression

C,R

Logical AND

ASC(character)

C,R

Returns the value of ASCII character

ATN(expression)

C,R

Returns the arctangent of expression

BAUD expression

C,R

Sets the baud rate for LPT (pin 8). For proper operation, XTAL must match the

system’s crystal frequency.

CALL integer

C,R

Calls an assembly-language routine at the specified address in program memory.

The Microcontroller Idea Book

75