beautypg.com

31 using jump tables (jmp @a+dptr) – Texas Instruments MSC1210 User Manual

Page 228

background image

Using Jump Tables (JMP @A+DPTR)

16-34

16.31 Using Jump Tables (JMP @A+DPTR)

A frequent method for quickly branching to many different areas in a program
is by using jump tables. For example, branching to different subroutines based
on the value of the accumulator could be accomplished with the CJNE instruc-
tion (which has already been covered):

CJNE A,#00h,CHECK1 ;If it’s not zero, jump to CHECK1

AJMP SUB0

;Go to SUB0 subroutine

CHECK1: CJNE A,#01h,CHECK2 ;If it’s not 1, jump to CHECK2

AJMP SUB1

;Go to SUB1 subroutine

CHECK2:

This code will work, but each additional possible value increases the size of
the program by 5 bytes—3 bytes for the CJNE instruction and 2 bytes for the
AJMP instruction.

A more efficient way is to create a jump table by using the JMP @A+DPTR
instruction. Like the MOVC @A+DPTR, this instruction calculates an address
by summing the accumulator and DPTR, and then jumps to that address.
Therefore, if DPTR holds 2000

H

and the accumulator holds 14

H

, the JMP

instruction jumps to 2014

H

.

Consider the following code:

RL A

;Rotate accumulator left, multiply by 2

MOV DPTR,#JUMP_TABLE

;Load DPTR with address of jump table

JMP @A+DPTR

;Jump to the corresponding address

JUMP_TABLE:

AJMP SUB0

;Jump table entry to SUB0

AJMP SUB1

This code first takes the value of the accumulator and multiplies it by two by shift-
ing the accumulator to the left by one bit. The accumulator must first be multiplied
by two because each AJMP entry in JUMP_TABLE is two bytes long,

The code then loads the DPTR with the address of the JUMP_TABLE and pro-
ceeds to JMP to the address of the accumulator plus DPTR. No additional
checks are necessary because we already know that we want to jump to the
offset indicated by the accumulator. We jump directly into the table that jumps
to our subroutine. Each additional entry in the jump table will require only two
additional bytes (two bytes for each AJMP instruction).

Note:

It is almost always a good idea to use a jump table if there are two or more
choices based on a zero-based index. A jump table with just two entries, like
the previous example, saves one byte of memory over using the CJNE ap-
proach, and saves three bytes of memory for each additional entry.