UMBC |
CMSC 391 -- Programming Microcontrollers |
|
Jump and Call Instructions
There are three control structures used in programming.
- Sequential
- Repetition
- Selection
Obviously, sequential is the easiest. However, that does not always accomplish
the task at hand. Sometimes, we need something else. It is necessary branch
in one of two directions. (Assembly language does not support a switch
like C language.) Actually, you set up the condition and test the results.
If the result is a certain thing, you branch to another location, otherwise,
the new instruction in the sequence is performed. What condition, a bit being
set, the result of a comparison (actually, something is zero or nonzero), or
a decrement and jump if zero. We can also do an unconditional branch or
call a function and return from it.
Next concern! How far do you have to jump?
- The target is within the range of (PC - 128) or (PC + 127). Notice this
is relative to the PC and is displacement is an signed byte. This uses
the SJMP instruction.
Other instructions are:
- JC - Jump if carry is set.
- JNC - Jump if carry is not set.
- JB - Jump if bit is set.
- JNB - Jump if bit is not set.
- JBC - Jump if bit is set and clear the bit.
- CJNE - Compare and jump if not equal
- DJNZ - Decrement and jump if not zero
- JZ - Jump if zero
- JNZ - Jump of not zero
- The target is within the same 2K block of memory. This is the Short
Absolute Range jump. 2K fits in eleven bits. Since an address is 16-bits,
the remaining 5 bits defines the block (or the page). This uses the AJMP
instruction.
- The target is somewhere in the 64K range of the 8051 memory. This uses the
LJMP instruction.
CJNZ has three operands, the first two are what is to be compared and the third
is the target of the jump if they are not the same. This instruction does not
allow a 16-bit address for any operand.
DJNZ is what we use for repetition. The only jump allowed is a relative jump.
If the loop is too big, put part of it into a function and call the function
so that the jump becomes small enough for a relative jump.
Subroutines
To use the subroutines, make sure you set the SP
register to point to a place where you are not going to affect any of the registers!
When a call is encountered, the two bytes of the PC register are put on the
stack. When the subroutine is finished, you -- the programmer -- MUST
put a RET instrction in your code that will cause the the return address to be
popped off the stack and put into the PC. Both the LCALL/ACALL and RET instructions
will automatically adjust the SP register. The stack grows up into the
high addresses when something is pushed and contracts when something is popped.
(There is also a PUSH and a POP instruction to put data on the stack for
temporary storage.)
©2004, Gary L. Burt