[h]SQUARE ROOTS WITH PICS - published in EPE Aug02

PETER HEMSLEY

A neat MPASM routine that allows a PIC microcontroller to extract the
square root of a number.

LISTING 1

; Find the square root of a 24-bit number in NUMH, NUMM, NUML
; 12-bit result in ROOTH, ROOTL
; Temporary variables: REMDRH, REMDRL, COUNT
; 40 instructions
; Execution time: about 326-387 cycles

SQRT   CLRF    ROOTL           ; Clear result
       CLRF    ROOTH
       CLRF    REMDRL          ; Clear work area
       CLRF    REMDRH
       MOVLW   0x0C            ; Loop counter
       MOVWF   COUNT
SQRLP  RLF     NUML            ; Shift two bits of
       RLF     NUMM            ; NUM into work
       RLF     NUMH            ; area
       RLF     REMDRL
       RLF     REMDRH
       RLF     NUML
       RLF     NUMM
       RLF     NUMH
       RLF     REMDRL
       RLF     REMDRH
       BCF     ROOTL,0         ; Clear prev test bit
       SETC                    ; Insert new test bit
       RLF     ROOTL
       RLF     ROOTH
       MOVFW   ROOTH           ; Compare root
       SUBWF   REMDRH,W        ; and remainder
       SKPZ
       GOTO    TSTGT
       MOVFW   ROOTL
       SUBWF   REMDRL,W
TSTGT  SKPC
       GOTO    REMLT
       MOVFW   ROOTL           ; Subtract root
       SUBWF   REMDRL          ; from remainder
       SKPC
       DECF    REMDRH
       MOVFW   ROOTH
       SUBWF   REMDRH
       BSF     ROOTL,1         ; Set root bit
REMLT  DECFSZ  COUNT
       GOTO    SQRLP           ; Next root bit
       CLRC
       RRF     ROOTH           ; Adjust root
       RRF     ROOTL
       RETURN