RETLW Control Flow
Return from a subroutine with a constant in W; the basis of lookup tables.
| Syntax | RETLW k |
|---|---|
| Operands | k: 8-bit literal 0-255 (0x00-0xFF) |
| Operation | k → W, top of stack → PC |
| Status bits | None |
| Words / cycles | 1 word, 2 cycles |
| Encoding | 11 01xx kkkk kkkk |
How it works
RETLW loads the literal k into W and returns from the subroutine. A lookup table is a subroutine that adds W to PCL to jump into a list of RETLW instructions, so the caller gets back the entry selected by W.
The DT directive builds such a list for you: DT 0x3F, 0x06 assembles to RETLW 0x3F, RETLW 0x06.
Example
; RETLW example from picsimulator.com/instructions/retlw.html
list p=16f84a
include <p16f84a.inc>
org 0
movlw 2
call table ; W = 0x5B, the 7-segment pattern for 2
movwf 0x20
done:
goto done
table:
addwf PCL, f ; jump W entries into the list
retlw 0x3F ; 0
retlw 0x06 ; 1
retlw 0x5B ; 2
retlw 0x4F ; 3
W = 2 selects the third entry, 0x5B.
Open this example in the simulator
Watch out for
- ADDWF PCL only changes the low 8 bits of the program counter. Keep tables inside one 256-word block, or set PCLATH to the table's high address byte first.