PIC Microcontoller Math Method

12 Bit Square Root

;**********************************************************************
;by Nikolai Golovchenko
;12 bit SQARE ROOT
;Input:
;ACCB0 - high byte
;ACCB1 - low byte
;Result:
;ACCB0 - 6bit
;Used:
;TEMPB0 - temporary for result
;TEMPB1 - temporary for input
;LOOPCNT - counter
;Memory used
;32 instructions
;5 RAM bytes
;11+17*5 + 16 + 6 = 118 cycles all cases
;**********************************************************************
Sqrt12	clrf TEMPB0	;clear all used
	clrf TEMPB1	;temporary registers
	movlw 6		;and setup counter
	movwf LOOPCNT	;
	
	swapf ACCB0, f	;Left justify
	swapf ACCB1, w	;12bit value
	andlw 0x0f	;in two byte
	iorwf ACCB0, f	;accumulator
	swapf ACCB1, w	;
	andlw 0xf0	;
	movwf ACCB1	;
Sqrt12a
	rlf ACCB1, f	;shift next
	rlf ACCB0, f	;two higher bits
	rlf TEMPB1, f	;of input
	rlf ACCB1, f	;to
	rlf ACCB0, f	;TEMPB1
	rlf TEMPB1, f	;

	movf TEMPB0, w	;take current result (shifted 2 bits left)
	addlw 0x01	;and OR with 01 (test bit) - addlw clears C
	rlf TEMPB0, f	;and reserve place for the next bit

	subwf TEMPB1, w	;test substraction for borrow
	btfsc _C
	 bsf TEMPB0, 2	;set next result bit if no borrow
	btfsc _C
	 movwf TEMPB1	;store substraction result if no borrow

	decfsz LOOPCNT	;repeat untill all 6 bits will be found
	 goto Sqrt12a

	bcf _C
	rrf TEMPB0, f	;right
	rrf TEMPB0, w	;justify the result
	movwf ACCB0	;and copy to result register
	return
;**********************************************************************
;Last updated 16Nov99

See: